I'm trying to pass env variable to service defined in docker compose file with DockerComposeContainer
final var compose = new DockerComposeContainer<>(new File("../docker-compose.yml"))
.withEnv(Map.of("MY_ENV_VAR", "test_value"))
.withLocalCompose(true);
compose.start();
But I can't see MY_ENV_VAR env variable in any of containers started by docker compose.
Also I can't find any docs explaining how withEnv
work with DockerComposeContainer.
How to properly pass env to container from docker compose file?
CodePudding user response:
Figured it out. Have to pass env. variable manually to required service inside docker-compose file:
# docker-compose.yml
services:
my-service:
environment:
MY_ENV_VAR: ${MY_ENV_VAR}
CodePudding user response:
The docker Compose Module documentation states the following.
Behind the scenes, Testcontainers actually launches a temporary Docker Compose client - in a container, of course, so it's not necessary to have it installed on all developer/test machines.
Since there's no documentation on the withEnv()
method, I went looking at the source and found this comment on the env
class field.
Properties that should be passed through to all Compose and ambassador containers (not necessarily to containers that are spawned by Compose itself)
As far as I understood, the environment variables passed using the withEnv()
method were applied to the container that runs the Docker Compose client. Hence, if you want to specify environment variables for spawned containers, you should use the Docker Compose configuration file to do it.
Edit
With the local Docker Compose instance, the environment variables are applied to the docker-compose command. Containers spawned by Docker Compose do not inherit environment variables from the client that requested their spawn. But, you can still inject client's environment variables into spawned containers using the configuration file.
version: "3.9"
services:
test:
image: busybox
environment:
TEST_ENV_VAR: ${TEST_ENV_VAR:default-value}
command: printenv
And then your Java code should be able to inject it as expected.
new DockerComposeContainer<>(new File("../docker-compose.yml"))
.withEnv(Map.of("TEST_ENV_VAR", "test_value"))
.withLocalCompose(true)
.start();