Environment & env_file
Most container images are configured through environment variables: the database password for Postgres, the
log level for your API, the URL of the cache. Compose gives you two keys to set them, environment (values written
in the Compose file) and env_file (values read from files). This lesson covers both syntaxes, the file format,
the order in which values override each other, and the one distinction that confuses nearly everyone: .env is
not the same as env_file.
Before you start: everything here is about variables inside the container. Variables used to fill in the
Compose file itself (${TAG}) are interpolation, the next lesson.
environment: map or list
You can write environment as a map or as a list of KEY=value strings. Compose turns both into the same map, and
every value into a string:
services:
map-style:
image: alpine:3.22
environment:
LOG_LEVEL: debug
WORKERS: 4
FEATURE_X: true
PASSTHROUGH:
list-style:
image: alpine:3.22
environment:
- LOG_LEVEL=debug
- WORKERS=4
- GREETING=hello world
- QUOTED="x"
- PASSTHROUGHname: demo
services:
list-style:
environment:
GREETING: hello world
LOG_LEVEL: debug
PASSTHROUGH: null
QUOTED: '"x"'
WORKERS: "4"
image: alpine:3.22
networks:
default: null
map-style:
environment:
FEATURE_X: "true"
LOG_LEVEL: debug
PASSTHROUGH: null
WORKERS: "4"
image: alpine:3.22
networks:
default: null
networks:
default:
name: demo_default
Two details:
- Values are strings in the container no matter what, but YAML types still bite:
truebecame"true", and as shown in The Compose File,1.10would become"1.1". Quote such values. PASSTHROUGHwithout a value (null) means "copy this variable from the shell that runs Compose, if it is set". If it isn't set, the container doesn't get the variable at all. This is handy for secrets you don't want in the file, such asAWS_PROFILE.
In the list form, everything after the first = is the value, including quotes: - QUOTED="x" set the value to
"x" with the quote characters (shown as '"x"' above). The map form doesn't have that trap.
env_file: values from files
env_file loads variables from one or more files, so the Compose file stays short and you can keep different
values per environment. The short form is a path or a list of paths; the long form adds required and format:
# $ docker compose config --no-path-resolution
services:
api:
image: shop/api:1.4
env_file:
- common.env
- path: api.env
- path: local.env
required: false
environment:
LOG_LEVEL: warning
# --- common.env
LOG_LEVEL=info
REGION=eu-west-1
TIMEOUT=30
# --- api.env
TIMEOUT=10
API_HOST=api.${REGION}.example.comname: demo
services:
api:
environment:
API_HOST: api.eu-west-1.example.com
LOG_LEVEL: warning
REGION: eu-west-1
TIMEOUT: "10"
image: shop/api:1.4
networks:
default: null
networks:
default:
name: demo_default
Follow each variable to its source:
LOG_LEVELisinfoincommon.env, butenvironmentwins:warning.TIMEOUTis in both files; the later file (api.env) wins:10.API_HOSTuses${REGION}, which Compose expanded from the earlier file.local.envdoesn't exist, andrequired: falsemakes that fine. It is the classic place for personal overrides that are listed in.gitignore.
Without required: false, a missing file is an error (here with --no-path-resolution, so the path stays
relative):
# $ docker compose config --no-path-resolution
services:
api:
image: shop/api:1.4
env_file: secrets.envenv file secrets.env not found: stat secrets.env: no such file or directory
The env file format
An env file has one KEY=value per line. Compose's parser understands more than you might expect:
# $ docker compose config --no-path-resolution
services:
api:
image: shop/api:1.4
env_file:
- app.env
- path: legacy.env
format: raw
# --- app.env
# full-line comments are ignored
GREETING="hello world"
QUOTED_HASH="a # b"
TRAILING=x # this comment is stripped
SINGLE='$NOT_EXPANDED'
export WORKERS=4
EMPTY=
MULTI="line1\nline2"
# --- legacy.env
RAW="kept as is" ${REGION}name: demo
services:
api:
environment:
EMPTY: ""
GREETING: hello world
MULTI: |-
line1
line2
QUOTED_HASH: 'a # b'
RAW: '"kept as is" ${REGION}'
SINGLE: $NOT_EXPANDED
TRAILING: x
WORKERS: "4"
image: shop/api:1.4
networks:
default: null
networks:
default:
name: demo_default
| Line | Result |
|---|---|
GREETING="hello world" |
double quotes are removed |
QUOTED_HASH="a # b" |
# inside quotes is kept |
TRAILING=x # … |
an unquoted # starts a comment |
SINGLE='$NOT_EXPANDED' |
single quotes: no interpolation; $ in the output is the escaped form of a literal $ |
export WORKERS=4 |
a leading export is allowed, so the file can also be sourced by a shell |
EMPTY= |
an empty string (the variable exists) |
MULTI="line1\nline2" |
\n in double quotes becomes a real newline |
format: raw |
no parsing at all: quotes and ${…} stay literally in the value |
.env is not env_file
This is the most common Compose misunderstanding, so it gets its own section:
.env (in the project folder) |
env_file: |
|
|---|---|---|
| Read | automatically, once per project | only when a service lists it |
| Used for | interpolating the Compose file (${TAG}) |
variables inside the container |
| Reaches the container? | no, unless the file references the variable | yes, every variable in it |
services:
api:
image: shop/api:${TAG}
environment:
LOG_LEVEL: ${LOG_LEVEL}
# --- .env
TAG=1.4.2
LOG_LEVEL=info
STRIPE_KEY=sk_test_only_in_dotenvname: demo
services:
api:
environment:
LOG_LEVEL: info
image: shop/api:1.4.2
networks:
default: null
networks:
default:
name: demo_default
STRIPE_KEY is in .env but appears nowhere in the result: nothing in the file asked for it, so the container
will never see it. LOG_LEVEL arrives only because environment references it. If you want a file's variables in
the container, list it under env_file (you may even list .env itself).
Precedence
When the same variable is set in several places, the highest-priority source wins:
docker compose run -e KEY=valueon the command lineenvironment:in the Compose file (after interpolation from the shell and.env)env_file:files, later files over earlier onesENVin the image's Dockerfile
The model applies those layers in order, from lowest to highest:
def resolve(image_env, env_files, environment, run_flags, shell):
final, source = {}, {}
layers = [("image ENV", image_env)]
layers += [(f"env_file {name}", values) for name, values in env_files]
layers += [("environment", environment), ("run -e", run_flags)]
for label, values in layers:
for key, value in values.items():
if value is None: # KEY without a value: copy from the shell, if set
if key not in shell:
continue
value = shell[key]
label += " (from shell)"
final[key], source[key] = value, label
return final, source
final, source = resolve(
image_env={"LOG_LEVEL": "info", "PORT": "8000", "PYTHONUNBUFFERED": "1"},
env_files=[("common.env", {"LOG_LEVEL": "debug", "TIMEOUT": "30"}),
("api.env", {"TIMEOUT": "10"})],
environment={"LOG_LEVEL": "warning", "AWS_PROFILE": None, "DEBUG_TOKEN": None},
run_flags={"PORT": "9000"},
shell={"AWS_PROFILE": "dev"},
)
for key in sorted(final):
print(f"{key:17}= {final[key]:8} <- {source[key]}")AWS_PROFILE = dev <- environment (from shell)
LOG_LEVEL = warning <- environment
PORT = 9000 <- run -e
PYTHONUNBUFFERED = 1 <- image ENV
TIMEOUT = 10 <- env_file api.env
DEBUG_TOKEN is missing from the result: it was a pass-through, and the shell didn't have it.
Keep secrets out of Git
- Commit an
example.envwith dummy values; keep the real*.envfiles in.gitignore. - Remember that anyone who can run
docker inspecton the host can read every environment variable of a container. For real secrets prefer Compose secrets, which mount files. docker compose configprints the resolved values, secrets included. Don't paste its output into tickets.
Learn more: Variables & Interpolation · Env files in the Docker course · ConfigMaps in Kubernetes
Test yourself
A variable is set in env_file and in environment. Which value does the container get?
- The env_file value
- The environment value
- Compose fails
- Whichever is longer
.env contains STRIPE_KEY, and nothing in compose.yaml mentions it. Does the container see STRIPE_KEY?
- Yes, .env is always injected
- No: .env is only used to interpolate the Compose file
- Only with --env-file
- Only in development
What does environment: [PASSTHROUGH] (no value) do if the shell has no PASSTHROUGH variable?
- Sets it to an empty string
- The container doesn't get the variable
- Compose fails
- Sets it to null