Docker Compose environment variables: precedence guide

Docker Compose has two related but different decisions to make: which values it uses while interpolating compose.yaml, and which environment variables finally reach a container. Keeping those stages separate makes the precedence rules much easier to reason about.
The quickest way to debug interpolation is docker compose config --environment. To inspect the fully resolved Compose model, run docker compose config.
Docker Compose interpolation syntax
Compose supports the following shell-style expressions inside compose.yaml:
| Expression | Result |
|---|---|
${VARIABLE} | Use the value, or an empty string if it is unset. |
${VARIABLE:-default} | Use default when the variable is unset or empty. |
${VARIABLE-default} | Use default only when the variable is unset. |
${VARIABLE:?error} | Exit with error when the variable is unset or empty. |
${VARIABLE?error} | Exit with error only when the variable is unset. |
${VARIABLE:+replacement} | Use replacement when the variable is set and non-empty. |
${VARIABLE+replacement} | Use replacement when the variable is set. |
Interpolation source precedence
When Compose substitutes ${VARIABLE} in the model, the sources are evaluated from highest to lowest priority:
- The shell environment where you run
docker compose. - Files passed with
--env-file, with later files overriding earlier ones. - The project
.envfile when--env-fileis not supplied.
An .env file supplies values for interpolation; it does not automatically put every value into the container. Reference a value under environment, or use a service-level env_file, when the container needs it.
services:
api:
image: example/api:${IMAGE_TAG:-latest}
environment:
NODE_ENV: ${NODE_ENV:-development}
Container environment variable precedence
For the final environment inside a container, the precedence is different. From highest to lowest:
docker compose run -e VARIABLE=value- An interpolated value in a service's
environmentorenv_fileattribute - A literal value in the service's
environmentattribute - A value in a service's
env_file - An
ENVvalue baked into the image
The host shell and project .env file do not create container variables by themselves. They become container values only when the Compose model references them.
Debug the value Compose will use
# Show the inputs used for interpolation
docker compose config --environment
# Render the resolved Compose model
docker compose config
# Inspect a variable in a one-off container
docker compose run --rm api env | grep NODE_ENV
For the complete matrix and edge cases, use Docker's current guides to variable interpolation and container environment precedence.