Environment variables let you run the same image with different settings. Compose uses them in two ways that are easy to mix up: setting variables inside a container, and filling in blanks in the Compose file.
Variables for the container
Use environment for individual values and env_file to load them from a file:
services:
web:
image: nginx:alpine
env_file:
- web.env
environment:
APP_MODE: productionweb.env holds one NAME=value pair per line. If the same name appears in both places, environment wins over env_file. Check what the container really received:
docker compose run --rm web printenv APP_MODEproductionInterpolation in the Compose file
Compose replaces ${NAME} in the file before creating anything:
services:
web:
image: nginx:${NGINX_TAG:-alpine}${NGINX_TAG:-alpine} uses alpine if the variable is unset or empty. ${NGINX_TAG:?set a tag} stops with that message instead.
Values can come from your shell or from a file named .env in the project directory:
NGINX_TAG=1.27-alpineA variable set in your shell takes priority over the same one in .env. Note that .env is for filling in the Compose file. Its contents do not enter containers unless you pass them, for example with environment or env_file.
To write a literal dollar sign in the Compose file, use $$.
See the result, protect secrets
docker compose config prints the file with values filled in, which is the quickest way to debug an empty variable:
docker compose configThat output can include passwords, so be careful where you paste it. Anyone who can inspect the container can also read its environment variables. Do not commit files holding real credentials to version control, and consider Compose secrets, which mount sensitive values as files.
Try it
Write the second example, then run docker compose config with no .env file and note the image tag. Add .env with NGINX_TAG=1.27-alpine and run it again. Finally, run NGINX_TAG=stable-alpine docker compose config and see which value wins.
Check your understanding
Environment Variables
All 3 sections · no timer
Unlimited retries
Questions from every section are combined into one assessment. Answer them all correctly to complete the article.
Your completion saves in this browser. Sign in to sync it to your account.