Compose Env Files & Variables
Compose uses environment variables in two different ways, and mixing them up is one of the most common sources of confusion:
- Interpolation:
${VAR}placeholders in the compose file itself are replaced before anything runs. Values come from your shell and from a file named.envnext to the compose file. - Container environment:
environment:andenv_file:set variables inside the containers.
# compose.yaml
services:
api:
image: "ghcr.io/acme/shop-api:${API_TAG:-latest}" # interpolation
ports:
- "${API_PORT:-8000}:8000" # interpolation
env_file:
- ./config/api.env # container environment
environment:
LOG_LEVEL: ${LOG_LEVEL:-info} # both: interpolated, then set in the container
DATABASE_URL: postgres://shop:${DB_PASSWORD:?set DB_PASSWORD in .env}@db/shop# .env (read automatically for interpolation)
API_TAG=2.4.1
DB_PASSWORD=dev-only-passwordCheck the result with docker compose config, which prints the fully resolved file. It is the first thing to run when a variable doesn't seem to apply.
Interpolation syntax
| Syntax | Result |
|---|---|
${VAR} or $VAR |
the value, or empty string if unset (with a warning) |
${VAR:-default} |
default if VAR is unset or empty |
${VAR-default} |
default only if VAR is unset |
${VAR:?message} |
error with message if unset or empty: great for required secrets |
${VAR:+other} |
other if VAR is set and non-empty, else empty |
$ |
a literal $ (for example in a shell command) |
Values for interpolation are looked up in the shell environment first, then in .env. So API_TAG=2.5.0 docker compose up beats the .env file.
import re
shell = {"API_PORT": "9000"}
dotenv = {"API_TAG": "2.4.1", "DB_PASSWORD": "dev-only-password", "API_PORT": "8000", "EMPTY": ""}
def lookup(name):
if name in shell:
return shell[name]
return dotenv.get(name) # None means unset
def interpolate(text):
def replace(m):
if m.group(0) == "$":
return "quot;
name, op, arg = m.group(1) or m.group(4), m.group(2), m.group(3)
value = lookup(name)
if op == ":-":
return value if value else arg
if op == "-":
return arg if value is None else value
if op == ":?":
if not value:
raise ValueError(f"required variable {name} is missing a value: {arg}")
return value
if op == ":+":
return arg if value else ""
return value or ""
return re.sub(r"\$\$|\$\{(\w+)(?:(:-|-|:\?|:\+)([^}]*))?\}|\$(\w+)", replace, text)
for line in ["ghcr.io/acme/shop-api:${API_TAG:-latest}",
"${API_PORT:-8000}:8000",
"LOG_LEVEL=${LOG_LEVEL:-info}",
"mode=[${EMPTY:-fallback}] vs [${EMPTY-fallback}]",
"postgres://shop:${DB_PASSWORD:?set it in .env}@db/shop",
"sh -c 'echo $HOME'",
"${SENTRY_DSN:?SENTRY_DSN is required}"]:
try:
print(f"{line:<55} => {interpolate(line)}")
except ValueError as e:
print(f"{line:<55} => error: {e}")ghcr.io/acme/shop-api:${API_TAG:-latest} => ghcr.io/acme/shop-api:2.4.1
${API_PORT:-8000}:8000 => 9000:8000
LOG_LEVEL=${LOG_LEVEL:-info} => LOG_LEVEL=info
mode=[${EMPTY:-fallback}] vs [${EMPTY-fallback}] => mode=[fallback] vs []
postgres://shop:${DB_PASSWORD:?set it in .env}@db/shop => postgres://shop:dev-only-password@db/shop
sh -c 'echo $HOME' => sh -c 'echo $HOME'
${SENTRY_DSN:?SENTRY_DSN is required} => error: required variable SENTRY_DSN is missing a value: SENTRY_DSN is required
API_PORT came from the shell (9000) even though .env says 8000. ${EMPTY-fallback} kept the empty value because the variable is set, just empty. And $HOME became $HOME, which the container's shell will expand.
Container environment precedence
Inside the container, several sources can define the same variable. Compose applies them in this order (later wins):
image ENV < env_file entries (in order) < environment: < docker compose run -eimage_env = {"PORT": "8000", "LOG_LEVEL": "warning", "TZ": "UTC"}
env_files = [
{"LOG_LEVEL": "info", "FEATURE_X": "off"}, # config/common.env
{"FEATURE_X": "on"}, # config/api.env
]
environment = {"LOG_LEVEL": "debug"}
run_flags = {} # docker compose run -e ...
final, source = {}, {}
for name, layer in [("image", image_env), ("common.env", env_files[0]),
("api.env", env_files[1]), ("environment", environment), ("-e", run_flags)]:
for key, value in layer.items():
final[key], source[key] = value, name
for key in sorted(final):
print(f"{key + '=' + final[key]:<16} (from {source[key]})")FEATURE_X=on (from api.env)
LOG_LEVEL=debug (from environment)
PORT=8000 (from image)
TZ=UTC (from image)
.env vs env_file: the key difference
.env next to compose.yaml |
env_file: in a service |
|
|---|---|---|
| Used for | interpolating ${...} in the compose file |
setting variables in that container |
| Reaches the container? | no, unless you reference the variable in environment: |
yes, every entry |
| Loaded | automatically (or --env-file other.env) |
only where listed |
So a DB_PASSWORD in .env is not visible inside containers by itself. That is a common surprise, and a good thing: you choose exactly which values reach which service.
Keep secrets out of Git
- Commit a
.env.examplewith placeholder values; add.envto.gitignore. - Use
${VAR:?message}for required values so a missing secret fails loudly atdocker compose up. - For real secrets, Compose supports
secrets:mounted as files (see Container Security):
services:
db:
image: postgres:17
environment:
POSTGRES_PASSWORD_FILE: /run/secrets/db_password
secrets: [db_password]
secrets:
db_password:
file: ./secrets/db_password.txtGo deeper: Environment & env_file and Variables & Interpolation in the Docker Compose course.
Test yourself
.env contains TAG=1.0 and you run TAG=2.0 docker compose up. Which value does ${TAG} in compose.yaml get?
- 1.0
- 2.0
- Empty
- An error
A variable defined only in .env is not visible inside the container. Why?
.envis broken.envis used for interpolating the compose file; values reach containers only viaenvironment:orenv_file:- Containers can't read environment variables
- It needs
exportin front
What does ${DB_PASSWORD:?missing} do when DB_PASSWORD is not set?
- Uses the text
missingas the password - Stops Compose with an error that includes
missing - Leaves it empty
- Prompts you for it