This is my compose.yaml
, and i don't have any .env
in my working dir.
services:
service_a:
image: "my_img"
environment:
- WORKER_NUMBER=1
stdin_open: true
tty: true
command: >
bash -c "export PATH=/root/miniconda3/bin:$PATH
&& conda init
&& echo "WORKER_NUMBER=${WORKER_NUMBER}"
&& tail -f /dev/null"
When i use docker compose up
i get a warning:
WARN[0000] The "WORKER_NUMBER" variable is not set. Defaulting to a blank string.
And the print result is
WORKER_NUMBER=
Why and how to set env var by environment
attribute correctly? Thanks for any helps!
My Docker & Docker compose ver:
Server: Docker Engine - Community
Engine:
Version: 19.03.15
Docker Compose version v2.27.0
UPDATE:
Fix the copy-paste error of echo cmd.
"environment:" adds the variables to the container, but referencing the variable as ${var} in the compose file gets compose to resolve it from the docker compose cli environment.
Rewrite the command as an array like this and escape the variables like this so they are resolved in the container:
services:
service_a:
image: "my_img"
environment:
- WORKER_NUMBER=1
stdin_open: true
tty: true
command:
- bash
- -c
- |
export PATH=/root/miniconda3/bin:$$PATH
conda init
echo "WORKER_NUMBER=$$WORKER_NUMBER"
tail -f /dev/null
alternatively, to supply WORKER from the outside:
WORKER=2 docker compose up
with the following changes will resolve "WORKER" as the compose file is being parsed. As shown, you can supply defaults.
services:
service_a:
environment:
- WORKER_NUMBER=${WORKER-0}
command:
- bash
- -c
- |
echo "WORKER_NUMBER=$$WORKER_NUMBER"
echo "WORKER=${WORKER}"
Reference: Interpolation (Compose Specification)