A project .env file only substitutes ${VAR} placeholders inside compose.yaml and puts nothing inside your container, whereas env_file injects runtime variables into the container without participating in YAML interpolation. Docker Compose resolves container values across six precedence levels from run -e down to unset, verifiable with docker compose config.
Contents
At a glance
- Class
- Tutorial
Provenance
- Aug 15, 2026Published
- Nov 14, 2026Last substantive update
By LK Wood IV · 2026-08-15 · Updated 2026-11-14 · ~12 min read · St. Louis County, MO
Drop a .env file next to compose.yaml, fill it with application settings, run docker compose up -d, and exec into the container to inspect env.
Nothing from .env is inside the container.
That single surprise wastes more homelab debugging hours than almost anything else in Docker. It happens because two Compose features share nearly identical names while operating at completely separate stages of container startup:
- Phase 1 — YAML Interpolation (
.envand--env-file): Substitutes${VAR}text placeholders insidecompose.yamlitself before Docker creates anything. By itself,.envinjects zero variables into any container. - Phase 2 — Container Runtime Injection (
env_file:andenvironment:): Passes key-value variables into the running container process, and is never consulted to fill${VAR}placeholders incompose.yaml.
Docker’s official precedence documentation states that distinction outright: the Host OS environment and .env file do not put a variable inside a container on their own unless compose.yaml explicitly references or passes them through.
YAML interpolation (.env) vs runtime injection (env_file:)
Before looking at precedence conflicts, separate the two mechanisms side by side. Mixing them up causes two silent bugs. Names look alike; directions stay opposite.
| Property | Project .env (or CLI --env-file) | Service env_file: attribute |
|---|---|---|
| When Compose reads it | Phase 1: Parsing compose.yaml | Phase 2: Creating the container runtime environment |
Fills ${VAR} in compose.yaml? (image:, ports:, volumes:) | Yes | No — completely ignored during YAML interpolation |
| Injects variables into the container? | No (unless wired into environment:) | Yes — every KEY=VAL line enters the container |
| Relative path base directory | --env-file resolves from your current shell working directory; default .env lives in the project directory | Resolves from compose.yaml’s parent folder, regardless of your shell pwd |
| If the file is missing | Default .env: silent no-op; explicit --env-file: hard error | Hard error by default (unless required: false on Compose 2.24+) |
Visible in docker compose config? | Shows interpolated values inside the rendered YAML | Expands and merges env_file: keys into the service’s rendered environment: block |
Here are both failure directions in ten lines of YAML:
# .env (Phase 1: YAML interpolation source ONLY)
POSTGRES_TAG=17-alpine
# compose.yaml
services:
db:
image: postgres:${POSTGRES_TAG} # Works: .env turns this into postgres:17-alpine
env_file:
- ./app.env # Works: every line in app.env enters the container
environment:
- TZ=America/Chicago # Works: TZ enters the container
In that file, POSTGRES_TAG never enters the db container’s env output. Now look at the mirror-image mistake:
services:
web:
image: "nginx:${NGINX_TAG}" # BROKEN: env_file is NOT read for ${NGINX_TAG}!
env_file:
- ./web.env # Even if NGINX_TAG=1.27 is inside web.env, image becomes "nginx:"
Listing ./web.env (or even ./.env) under env_file: dumps every key into the container process at runtime, while ${NGINX_TAG} on the image: line still evaluates before env_file: is ever opened.
Complete 6-level Docker Compose variable precedence table
When the same variable name appears in more than one place, Docker’s environment variable precedence specification resolves what actually lands inside the container from Level 1 (highest) down to Level 6 (lowest):
| Priority | Mechanism | Example | Critical edge case to watch |
|---|---|---|---|
| 1 (Highest) | docker compose run -e CLI flag | docker compose run --rm -e APP_ENV=cli_run web env | Applies only to docker compose run one-off containers (docker compose up has no -e flag). Bare -e VAR pulls from host shell. |
| 2 | Host shell environment (passed or interpolated into service) | APP_ENV=host_shell docker compose up -d with environment: [APP_ENV] or APP_ENV=${APP_ENV} | Host shell beats .env during ${VAR} interpolation AND beats env_file: when bare environment: - APP_ENV is listed. Unexported shell vars are invisible! |
| 3 | Service environment: attribute in compose.yaml | environment: [APP_ENV=compose_attr] (literal or .env-interpolated) | Beats env_file: even when empty! A stray APP_ENV= or APP_ENV: "${UNSET}" under environment: wipes out a valid APP_ENV in env_file:. |
| 4 | Service env_file: attribute in compose.yaml | env_file: [./base.env, ./local.env] | Evaluated top-to-bottom when multiple files are listed; the last file in the env_file: list wins (local.env beats base.env). |
| 5 | Container image Dockerfile ENV | ENV APP_ENV=image_default baked into image layers | Pure fallback. Evaluates only if Levels 1–4 have zero entry for APP_ENV. Any Compose entry replaces it completely. |
| 6 (Lowest) | Unset / undefined | Variable omitted everywhere | Absent from container env. If referenced via unguarded ${VAR} in YAML, silently becomes empty string ""! |
Keep Phase 1 YAML interpolation precedence distinct in your head too (variable interpolation docs). When Compose fills ${VAR} inside compose.yaml, it checks three sources in order:
- Host OS shell environment (
export VAR=...or inlineVAR=... docker compose ...) - CLI
--env-filefile(s) (orCOMPOSE_ENV_FILES; if passed multiple times, the last--env-filewins) - Default
.envfile in the project directory (unless disabled viaCOMPOSE_DISABLE_ENV_FILE=1)
Verify all 6 levels yourself with docker compose config
Never guess what Compose resolved. Never test with live database passwords either. Create a disposable lab directory with distinct, non-secret marker strings (FROM_DOTENV, FROM_ENV_FILE, FROM_COMPOSE_ENV, FROM_HOST_SHELL, FROM_RUN_CLI) and inspect the merged model using docker compose config:
mkdir -p /tmp/compose-env-lab && cd /tmp/compose-env-lab
cat > .env <<'EOF'
IMAGE_TAG=3.20
TEST_INTERPOLATED=FROM_DOTENV
EOF
cat > runtime.env <<'EOF'
TEST_FILE_ONLY=FROM_ENV_FILE
TEST_CONFLICT=FROM_ENV_FILE
TEST_EMPTY_TRAP=GOOD_VALUE_IN_ENV_FILE
EOF
cat > compose.yaml <<'EOF'
services:
probe:
image: alpine:${IMAGE_TAG}
env_file:
- ./runtime.env
environment:
TEST_CONFLICT: FROM_COMPOSE_ENV
TEST_SHELL_BRIDGE: ${TEST_INTERPOLATED}
TEST_EMPTY_TRAP: ""
EOF
Run docker compose config before starting any container:
docker compose config
Look at the rendered environment: block Compose prints for probe:
imageresolved toalpine:3.20, whileIMAGE_TAGitself is absent fromenvironment:(proving.envalone stays out of the container).TEST_FILE_ONLYequalsFROM_ENV_FILE(Level 4).TEST_CONFLICTequalsFROM_COMPOSE_ENV(Level 3 beat Level 4).TEST_SHELL_BRIDGEequalsFROM_DOTENV(.envinterpolated${TEST_INTERPOLATED}into Level 3).TEST_EMPTY_TRAPequals""(an empty string in Level 3 wiped outGOOD_VALUE_IN_ENV_FILEfrom Level 4 with zero warnings!).
Now watch Levels 2 and 1 override that same stack live without editing a file:
# Level 2: Host shell overrides .env interpolation -> prints TEST_SHELL_BRIDGE=FROM_HOST_SHELL
TEST_INTERPOLATED=FROM_HOST_SHELL docker compose run --rm probe sh -c 'env | grep ^TEST_ | sort'
# Level 1: run -e beats everything -> prints TEST_CONFLICT=FROM_RUN_CLI
docker compose run --rm -e TEST_CONFLICT=FROM_RUN_CLI probe sh -c 'env | grep ^TEST_ | sort'
# Clean up the scratch folder when finished
rm -rf /tmp/compose-env-lab
Whenever a stack behaves strangely on your server (whether managed from the CLI or via Dockge), docker compose config and docker compose config --environment show the exact post-interpolation truth in two seconds. Keep docker compose config output out of public GitHub issues or screenshots if real credentials sit in your env files, because Compose prints every resolved value inline!
env_file: multi-file layering, required: false, and format: raw
Modern Compose v2 (services env_file reference) supports a structured mapping syntax under env_file: that solves two classic parser headaches:
services:
webapp:
env_file:
- ./defaults.env
- path: ./local-overrides.env
required: false # Compose 2.24.0+: silent skip if missing
- path: ./literal-hashes.env
format: raw # Compose 2.30.0+: no quote stripping or $ expansion!
Pay close attention to format: raw (added in Compose 2.30.0). In standard .env and env_file syntax, double-quoted and unquoted values expand $ signs—so a bcrypt password hash like $2a$12$R9h/cIPz0gi... gets mangled into $R9h/cIPz0gi... unless wrapped in single quotes ('$2a$12...'), escaped as $$, or loaded via format: raw. Also watch inline comments: PORT=8080 # web sets 8080, whereas PORT=8080# web (missing the space before #) sets the literal string 8080# web.
Guarding defaults: ${VAR:-default} vs ${VAR-default} vs ${VAR:?error}
Never leave critical image tags or database usernames as bare ${VAR} placeholders. An unset ${POSTGRES_VERSION} turns postgres:${POSTGRES_VERSION} into postgres:, producing a cryptic registry parse error instead of telling you which variable was missing.
The colon inside parameter expansion controls whether empty strings (VAR="") trigger the fallback alongside unset variables:
| Syntax | Variable is unset | Variable is empty (VAR=) | Variable is VAR=custom | Best use in compose.yaml |
|---|---|---|---|---|
${VAR:-default} | "default" | "default" | "custom" | Safe defaults for image tags, ports, and optional settings |
${VAR-default} | "default" | "" (stays empty!) | "custom" | Rare cases where an explicit empty string is intentional |
${VAR:?error msg} | Fails fast with error msg | Fails fast with error msg | "custom" | Required paths, hostnames, and non-default usernames |
${VAR?error msg} | Fails fast with error msg | "" (allowed!) | "custom" | Required key that is allowed to be blank |
services:
db:
image: "postgres:${POSTGRES_VERSION:-17}"
environment:
POSTGRES_DB: "${DB_NAME:-app}"
POSTGRES_USER: "${DB_USER:?Set DB_USER in .env before starting}"
Also note the warning difference on pass-through lines: writing bare - DEBUG under environment: emits zero warning when DEBUG is unset in your shell, whereas writing - DEBUG=${DEBUG} prints an explicit WARN[0000] The "DEBUG" variable is not set. Defaulting to a blank string. Use the explicit ${VAR:?...} or ${VAR:-...} forms so missing .env files on a new server fail loud at docker compose up time rather than half-starting a broken container.
Keep real secrets out of environment variables
Everything injected via environment: or env_file: is stored in container metadata and returned in plaintext by docker inspect. On Linux, anyone in the docker group can inspect every running container—and crashed apps routinely dump process.env or os.environ into stack traces. Build-time ARG tokens are even worse, remaining baked into docker history image metadata unless handled via BuildKit secret mounts.
Where official images support the _FILE convention (postgres, mariadb, mysql, wordpress, authelia, vaultwarden admin tokens), mount file-based Compose secrets into /run/secrets/<name> as recommended in Docker’s environment-variable best practices:
services:
db:
image: postgres:17
environment:
POSTGRES_USER: appuser
POSTGRES_PASSWORD_FILE: /run/secrets/db_password
secrets:
- db_password
secrets:
db_password:
file: ./secrets/db_password.txt # chmod 600 on host, gitignored
My three-rule house standard
After getting burned once at 1 a.m. by an empty environment: key overriding a valid env_file: entry, I stick to three non-negotiable habits on every homelab stack:
.envshapescompose.yamlonly: Pinned image versions (IMMICH_VERSION), published host ports, and host bind-mount paths (UPLOAD_LOCATION) live in.env, guarded by:-defaults or:?checks.env_file:feeds application config: App-internal flags go into a dedicated./app.env(withchmod 600), while actual credentials use/run/secrets/_FILEmounts wherever supported.- Never define the same variable name in both
environment:andenv_file:: Precedence tables are for diagnosing bugs—not for intentionally defining conflicting values across two files and hoping future-you remembers Level 3 beats Level 4. While tidying up old stacks, check unused volumes and dangling images with our Docker disk-space cleanup guide.
Sources
- Docker Compose Environment Variables Precedence — official 6-level container precedence table and
.env/ host OS illustration boundary. - Set Environment Variables in Docker Compose and Compose
env_fileReference —environment:vsenv_file:,required: false(2.24+), andformat: raw(2.30+). - Variable Interpolation in Docker Compose and Pre-defined Environment Variables —
${VAR:-default},${VAR:?err},COMPOSE_ENV_FILES, andCOMPOSE_DISABLE_ENV_FILE. docker compose configCLI Reference and Environment Variables Best Practices.
Frequently asked questions
Does a .env file automatically set variables in my container?
What is the difference between .env and env_file?
What is the 6-level precedence order for environment variables in Docker Compose?
Does environment beat env_file when empty?
Why did my image tag fail with invalid reference format?
When does a Dockerfile ENV apply?
Should I put database passwords in environment variables?
Why does a missing –env-file error out while a missing .env stays silent?
Corrections
- Last updated
- Methodology
- See our methodology for research and review standards.
- Corrections
- Spotted an error? Email a correction with the affected line and what you found. The draft includes this page’s address. Verified changes are recorded here. Contact details.