Variables and configuration
Two different kinds of "environment"
People mix these up constantly:
- Interpolation variables —
${TAG}inside the compose file, substituted when Compose parses the file. Sources: your shell environment, then the.envfile in the project directory (or--env-file). - Container environment — variables set inside the container via
environment:andenv_file:.
The .env file is not passed into containers automatically; it only feeds interpolation. env_file: .env passes it into a container explicitly.
Interpolation syntax
image: shop-api:${TAG} # empty string if unset (with a warning)
image: shop-api:${TAG:-dev} # default if unset OR empty
image: shop-api:${TAG-dev} # default only if unset
image: shop-api:${TAG:?TAG is required} # fail with an error if unset/empty
command: echo $$HOME # $$ = literal $, evaluated in the container
Precedence for container environment
From highest to lowest: values set with docker compose run -e, then environment:, then env_file:, then the image's ENV. Shell variables beat .env for interpolation.
Use docker compose config to print the fully resolved file — the fastest way to debug "why does my container have the wrong value?".
Secrets
Compose secrets: mount a file read-only at /run/secrets/<name>. Many official images support *_FILE variables (POSTGRES_PASSWORD_FILE) for this. Locally the source is just a file, so this isn't encryption — but it keeps secrets out of docker inspect output and the compose file, and builds the habit of file-based secrets that maps to Kubernetes and Swarm.
Watch out: a password committed in
compose.yamlor.envis leaked even after you delete it — it lives in Git history. Remove it, rotate the credential, and add.envto.gitignore(commit a.env.exampleinstead).