Docker Compose .env files and variables: the two mechanisms
Hardcoding values in your compose.yaml makes it painful to reuse across environments, and committing secrets to Git is worse. Docker Compose gives you two distinct mechanisms that people often confuse: setting variables inside the container's environment, and interpolating variables into the Compose file itself. This guide separates the two, based on the official Docker docs.
1. Set variables in the container: the environment attribute
A container's environment is not set until you add an explicit entry in the service configuration. The environment attribute supports both mapping and list syntax:
services:
web:
image: "webapp:v1.5"
environment:
DEBUG: "true"
APP_ENV: production
You can also point to a file with env_file, whose lines become container environment variables. Paths in env_file are relative to your compose.yaml, you can list several files, and since Compose 2.24.0 you can mark one optional with required: false so a missing file is silently ignored.
2. Interpolate variables into the Compose file: .env
Interpolation inserts values into compose.yaml at runtime. Compose reads a .env file in the project directory by default, and you reference values with ${...}:
# .env
TAG=v1.5
# compose.yaml
services:
web:
image: "webapp:${TAG}"
Run docker compose config to print the resolved configuration and verify exactly what Compose will use. This is the fastest way to debug a value that is not what you expected.
3. Precedence: when several sources set the same variable
The same variable can be declared in multiple places: your shell, the .env file, the environment attribute, env_file. When sources collide, Compose applies a defined precedence order instead of using them randomly. If a value surprises you, do not guess which source won: run docker compose config and read the resolved output.
4. Keep secrets out of Git
The Docker docs warn directly: do not use environment variables to pass sensitive information such as passwords into containers; use secrets instead. Practically: commit compose.yaml, keep real values in an untracked .env, and add .env to your .gitignore (see our .gitignore guide).
Which one do I use?
| Goal | Mechanism |
|---|---|
| App reads the value inside the container | environment or env_file |
| Change image tags, ports, volume paths per machine | .env interpolation with ${VAR} |
| Passwords, tokens, keys | Secrets, not environment variables |
Common mistakes
- Editing
.envand expecting the container to see new values withoutdocker compose upagain. - Committing
.envwith real credentials. - Debugging by guessing instead of running
docker compose config.
Related reads: this guide's source docs below, and fixing nginx 502 Bad Gateway when the stack is up but the proxy fails.
