Sub topic 9
Parameterizing with variables and env files
This chapter assumes you can read a Compose file, know what an environment variable is, and have used docker compose up and docker compose config. It covers how Compose fills in ${...} placeholders, where it looks for values, and how that supports the override files and profiles from earlier chapters.
Why parameterize
Override files change the structure of a project, such as which services run and which volumes are mounted. Many differences are only values: an image tag, a published port, a password, a log level. Copying a whole override file to change one number is wasteful. Variables let one file serve several environments, and each environment supplies its own values.
Compose does this with interpolation. Before it builds the configuration, it replaces placeholders in the Compose files with values from the environment.
Interpolation syntax
Compose supports these forms inside a Compose file:
| Syntax | Meaning |
|---|---|
| `${VAR}` or `$VAR` | The value of `VAR`, or an empty string if it is unset (Compose prints a warning). |
| `${VAR:-default}` | `default` if `VAR` is unset or empty. |
| `${VAR-default}` | `default` only if `VAR` is unset. An empty value is kept. |
| `${VAR:?message}` | Stop with `message` if `VAR` is unset or empty. |
| `${VAR?message}` | Stop with `message` only if `VAR` is unset. |
| `${VAR:+replacement}` | `replacement` if `VAR` is set and not empty, otherwise empty. |
| `$$` | A literal `$`, not interpolated. |
The braced form is safer. $VAR ends at the first character that cannot be part of a name, which can surprise you inside longer strings.
Here is a base file that uses several of these forms:
# compose.yaml
services:
web:
image: example/web:${WEB_TAG:-1.0}
ports:
- "${WEB_PORT:-8000}:8000"
environment:
LOG_LEVEL: ${LOG_LEVEL:-info}
depends_on:
- db
db:
image: postgres:16
environment:
POSTGRES_PASSWORD: ${DB_PASSWORD:?set DB_PASSWORD}
volumes:
- db-data:/var/lib/postgresql/data
volumes:
db-data:With nothing set, the project fails at startup with the message set DB_PASSWORD. That is intended. A missing secret stops the run instead of starting a database with an empty password.
Where values come from
Compose looks for interpolation values in this order. The first match wins:
- The shell environment of the
docker composeprocess. - Files named with
--env-file, or the default.envfile if you gave no--env-file. - The default written in the file, such as
:-info.
Shell values beat file values. That lets you override a setting for one command without editing any file:
LOG_LEVEL=debug docker compose up -dThe default .env file
If you do not pass --env-file, Compose reads a file named .env from the project directory. By default that is the directory of the first Compose file. You can change it with --project-directory.
# .env
DB_PASSWORD=dev-only-password
WEB_PORT=8000
LOG_LEVEL=debugThe lines are KEY=value, one per line, with # for comments. Quotes are allowed. Because .env is loaded without any flag, docker compose up in a development checkout works with no extra typing.
Choosing env files per environment
--env-file points Compose at a specific file. When you use it, Compose does not read the default .env. You can pass the flag several times, and later files win over earlier ones:
docker compose --env-file .env --env-file .env.prod \
-f compose.yaml -f compose.prod.yaml up -dHere .env is listed explicitly to keep shared defaults, and .env.prod overrides them. The same selection works through the COMPOSE_ENV_FILES variable, with a comma-separated list.
A common layout is one env file per environment:
.env # developer defaults, loaded automatically
.env.test # CI values
.env.prod # production values, kept out of Git or generated at deploy time
.env.example # committed template listing every variable with dummy valuesSettings Compose reads from the environment
Some variables configure Compose itself, and they can live in .env too. Examples are COMPOSE_FILE, COMPOSE_PROFILES, and COMPOSE_PROJECT_NAME. A development .env can contain:
# .env
COMPOSE_PROFILES=debug
COMPOSE_PROJECT_NAME=shopThis activates the debug profile for every command in that directory. The shell still wins, so COMPOSE_PROFILES= docker compose up turns it off for one command.
env_file and environment are different
The service attribute env_file looks similar but does a different job. It passes variables into the container. It does not feed interpolation of the Compose file.
services:
web:
image: example/web:${WEB_TAG:-1.0}
env_file:
- web.env
environment:
LOG_LEVEL: ${LOG_LEVEL:-info}Here ${WEB_TAG} is looked up in the shell and in .env. It is not looked up in web.env. The contents of web.env become container variables, and LOG_LEVEL under environment replaces any LOG_LEVEL from web.env.
For variables inside the container, the precedence from highest to lowest is:
docker compose run -e KEY=value- The
environmentattribute in the (merged) Compose file - The
env_fileattribute ENVin the image's Dockerfile
Two practical rules follow. Use .env and --env-file to choose values for the Compose file. Use env_file to hand a block of settings to a container.
If a file listed in env_file may not exist, Compose versions that support the long form let you mark it optional:
services:
web:
image: example/web:1.0
env_file:
- path: web.env
required: falseWithout required: false, a missing file is an error.
Variables with overrides and profiles
Interpolation works in every file you load, so it combines with the earlier techniques. Values are resolved as each file is read, and the merge happens afterward.
A production override can leave environment-specific values to variables:
# compose.prod.yaml
services:
web:
image: example/web:${WEB_TAG:?set WEB_TAG for production}
restart: unless-stopped
environment:
LOG_LEVEL: ${LOG_LEVEL:-warning}
db:
restart: unless-stoppedRequiring WEB_TAG in production avoids deploying whatever latest happens to be. The development files can stay lenient.
Variables can also drive profiles. Profile names are not interpolated, but the activation setting is a variable, so COMPOSE_PROFILES in an env file selects the optional services for that environment. Here is a CI example:
# .env.ci
DB_PASSWORD=ci-only-password
WEB_TAG=ci
COMPOSE_PROFILES=toolsdocker compose --env-file .env.ci -f compose.yaml up -d
docker compose --env-file .env.ci run --rm migrateThe first command starts web and db. The second runs the migrate service from the tools profile. Naming a profiled service in run activates its profile anyway.
Checking what Compose resolved
Use docker compose config after changing any variable. It prints the merged, interpolated result, so you see the actual image tag, ports, and environment:
docker compose --env-file .env.prod -f compose.yaml -f compose.prod.yaml configTwo details are worth knowing:
configprints resolved secrets in clear text. Do not paste its output into tickets or CI logs unfiltered.- To see the placeholders unchanged, run
docker compose config --no-interpolate. This helps when you cannot tell whether a wrong value came from the file or from the environment.
Common errors
- Warning: "The X variable is not set. Defaulting to a blank string." The placeholder had no default and no value was found. Add a default, set the variable, or use
:?to make it a hard error. - A change to
.envhas no effect. A shell variable with the same name is taking precedence. Runenv | grep NAMEand unset it. You may also have passed--env-file, which means.envis no longer read. .envis not found. Compose looks in the project directory, not necessarily the current directory. If you run with-f path/to/compose.yamlfrom elsewhere, the.envnext to that file is used. Add--project-directoryor--env-fileto be explicit.- A variable works in the Compose file but is missing in the container. Interpolation is not the container environment. Add it under
environmentorenv_file. - A literal
$disappears. Write$$. This is common in shell commands insidecommandorhealthcheckentries. - Empty string versus unset.
${VAR-default}keeps an empty value, while${VAR:-default}replaces it. IfKEY=appears in your env file, the two forms behave differently.
Summary of the design
Use files for structure, profiles for optional services, and variables for values. Keep shared defaults in the base file with :- defaults, mark secrets and release-critical values with :?, and keep one env file per environment. Check each combination with docker compose config before you run it.
Exercise
A base file has image: example/web:${WEB_TAG:-1.0}. The shell has no WEB_TAG. The file .env contains WEB_TAG= (empty), and .env.prod contains WEB_TAG=2.3. What image tag results from (a) docker compose up, (b) docker compose --env-file .env.prod up, and (c) WEB_TAG=3.0 docker compose --env-file .env.prod up? If the base file used ${WEB_TAG-1.0} instead, what would (a) give?
Show answer
(a) 1.0. .env is read, but WEB_TAG is empty, and :- treats an empty value like an unset one, so the default applies. (b) 2.3. With --env-file, .env is not read and .env.prod supplies the value. (c) 3.0. The shell environment beats env files. With ${WEB_TAG-1.0}, case (a) gives an empty tag, because the variable is set (to an empty string), so the default is not used and the image reference becomes example/web:, which is invalid.
Exercise
Your web service has env_file: [web.env], and web.env contains DB_HOST=db. Your Compose file also says image: example/web:${DB_HOST}. Is DB_HOST in web.env used for the image tag? Where must the value come from instead?
Show answer
No. env_file only sets variables inside the container. Interpolation of the Compose file reads the shell environment and .env or the --env-file files. To fill the image tag, put DB_HOST in the shell or in .env, or give the placeholder a default.