Docker Compose environment precedence and file-based secrets
Verify Docker Compose's two-stage precedence across .env, env_file, and environment, then inject database passwords safely with file-based secrets.
A
.envfile in your project root only interpolatescompose.yaml—it doesn’t inject variables into running containers. This post verifies Docker Compose’s two-stage precedence across.env,env_file, andenvironment, then comparessecretswith*_FILEinjection against plain environment variables on Docker Engine 29.9.3 and Docker Compose v5.7.1.
Every command and output below comes from running
alpine:3.21andpostgres:16-alpinecontainers onDocker Engine 29.9.3andDocker Compose v5.7.1.LabOnly_PgPass_2026!is a lab-only placeholder, not a real credential.
Why .env values stay out of your container
One of the most common Docker Compose surprises happens right after you create a .env file. You add ONLY_IN_DOTENV=from_dotenv in the project root, run docker compose up -d, and check env inside the container—only to find the variable missing.
Docker Compose splits environment handling into two stages: YAML interpolation and container injection. The root .env file feeds ${VAR} expressions inside compose.yaml, and Compose doesn’t copy its keys into container processes automatically.
flowchart TD
S1["Stage 1: Interpolation\nShell > --env-file > .env"] --> Y["Render compose.yaml"]
Y --> S2["Stage 2: Container Injection\nenvironment > env_file"]
IMG["Image Dockerfile ENV"] --> S2
S2 --> C["Container process env"]
You can verify this behavior with a minimal two-variable .env file where compose.yaml references only SHARED_VAR:
# .env
ONLY_IN_DOTENV=from_dotenv
SHARED_VAR=from_dotenv
1
2
3
4
5
6
7
8
9
# compose.yaml
name: env-secrets-lab
services:
app:
image: alpine:3.21
command: ["sleep", "300"]
environment:
- SHARED_VAR=${SHARED_VAR}
Inspecting the running container shows SHARED_VAR, while ONLY_IN_DOTENV never enters the container environment:
1
2
docker compose up -d
docker compose exec -T app env | sort
1
2
3
4
HOME=/root
HOSTNAME=dc2a87c52947
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
SHARED_VAR=from_dotenv
Running grep -E "^ONLY_IN_DOTENV=" inside the container prints nothing and exits with code 1. If you actually want every key from .env inside the container, declare env_file: .env on the service explicitly.
Verifying the two-stage precedence order
Real projects rarely have a single source of truth. Shell variables, --env-file, root .env, environment, multiple env_file entries, and Dockerfile ENV instructions often overlap. To see which source wins in every case, I set up five keys across all layers and ran the stack under three CLI invocations.
1
2
3
4
5
6
7
8
# Dockerfile
FROM alpine:3.21
ENV APP_MODE=from_image \
DB_HOST=from_image \
LOG_LEVEL=from_image \
IMAGE_ONLY=from_image \
ENV_FILE_ORDER=from_image
CMD ["sleep", "300"]
# base.env
APP_MODE=from_env_file_1
DB_HOST=from_env_file_1
LOG_LEVEL=from_env_file_1
ENV_FILE_ORDER=from_env_file_1
# override.env
LOG_LEVEL=from_env_file_2
ENV_FILE_ORDER=from_env_file_2
# .env
APP_MODE=from_dotenv
DB_HOST=from_dotenv
LOG_LEVEL=from_dotenv
# custom.env (used with --env-file)
APP_MODE=from_custom_env_file
DB_HOST=from_custom_env_file
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# compose.yaml
name: env-secrets-lab
services:
app:
build: .
env_file:
- ./base.env
- ./override.env
environment:
APP_MODE: ${APP_MODE}
DB_HOST: from_environment
app-list:
build: .
env_file:
- ./base.env
- ./override.env
environment:
- APP_MODE
- DB_HOST=from_environment_list
Here are the winning values observed from docker compose exec -T app env across default startup, --env-file custom.env, and an inline shell override (APP_MODE=from_shell):
| Variable | Default run | --env-file custom.env | APP_MODE=from_shell | Winning layer |
|---|---|---|---|---|
IMAGE_ONLY | from_image | from_image | from_image | Dockerfile ENV |
ENV_FILE_ORDER | from_env_file_2 | from_env_file_2 | from_env_file_2 | env_file (later file wins) |
LOG_LEVEL | from_env_file_2 | from_env_file_2 | from_env_file_2 | env_file (unreferenced in YAML) |
DB_HOST | from_environment | from_environment | from_environment | environment literal |
APP_MODE | from_dotenv | from_custom_env_file | from_shell | Interpolation (shell > --env-file > .env) |
1
2
3
APP_MODE=from_shell docker compose --env-file custom.env up -d
APP_MODE=from_shell docker compose --env-file custom.env exec -T app env \
| grep -E '^(APP_MODE|DB_HOST|LOG_LEVEL|IMAGE_ONLY|ENV_FILE_ORDER)=' | sort
1
2
3
4
5
APP_MODE=from_shell
DB_HOST=from_environment
ENV_FILE_ORDER=from_env_file_2
IMAGE_ONLY=from_image
LOG_LEVEL=from_env_file_2
Three rules explain every row in that table:
- YAML interpolation order:
shell environment > --env-file > root .env. Passing--env-filereplaces the default.envfile rather than merging with it. - Container injection order:
environment > env_file (last file wins) > Dockerfile ENV. Both mapping syntax (APP_MODE: ${APP_MODE}) and passthrough list syntax (- APP_MODEinapp-list) follow the exact same interpolation precedence. - Unreferenced
.envkeys never overrideenv_file: Even though.envsetsLOG_LEVEL=from_dotenv,compose.yamlnever references${LOG_LEVEL}, sooverride.envkeepsfrom_env_file_2.
When you want to preview the merged result before starting containers, docker compose config shows the resolved environment and env_file keys—just as I use it when splitting local environments in Separating local dev environments with Docker Compose Profiles and Override. Keep in mind that docker compose config doesn’t inspect the image itself, so image-only defaults like IMAGE_ONLY won’t appear in its output.
Interpolation defaults and required variable checks
Leaving a variable blank (VAR="") behaves differently from leaving it unset, and mixing up the syntax lets empty strings slip into production configs. I tested :-, -, and :? with docker compose config:
1
2
3
4
5
6
7
8
# compose-default.yaml
services:
app:
image: alpine:3.21
command: ["sleep", "60"]
environment:
COLON_DASH: ${OPT_VAR:-default_when_unset_or_empty}
PLAIN_DASH: ${OPT_VAR-default_only_when_unset}
1
2
3
4
5
6
7
# compose-required.yaml
services:
app:
image: alpine:3.21
command: ["sleep", "60"]
environment:
API_KEY: ${API_KEY:?API_KEY must be set and non-empty}
| Syntax | When unset | When empty (VAR="") | Best fit |
|---|---|---|---|
${VAR:-default} | default | default | Ports, log levels, or any option where blank means fallback |
${VAR-default} | default | "" (stays empty) | Options where an empty string has a distinct meaning |
${VAR:?message} | Fails (exit 1) | Fails (exit 1) | Required API keys or URLs that must block startup |
Running OPT_VAR="" docker compose -f compose-default.yaml config resolves COLON_DASH to default_when_unset_or_empty and leaves PLAIN_DASH as "". Running compose-required.yaml with API_KEY unset or empty aborts immediately before any container starts:
1
docker compose -f compose-required.yaml config
1
error while interpolating services.app.environment.API_KEY: required variable API_KEY is missing a value: API_KEY must be set and non-empty
Failing during config parsing beats letting a container boot with an empty string and crash minutes later on its first authenticated request.
Keeping passwords out of Config.Env with secrets
Passing database passwords through environment: puts plaintext credentials into container metadata. Anyone who runs docker inspect, collects container specs in a monitoring agent, or shares a docker compose config dump sees the secret directly.
Official database images such as postgres, mysql, and mariadb support *_FILE environment variables that read the actual value from a mounted file. To compare both approaches side by side, I ran db-insecure (POSTGRES_PASSWORD) alongside db-secure (POSTGRES_PASSWORD_FILE + secrets).
1
2
3
mkdir -p secrets
printf '%s' 'LabOnly_PgPass_2026!' > ./secrets/db_password.txt
chmod 600 ./secrets/db_password.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# compose.yaml
name: env-secrets-lab
services:
db-insecure:
image: postgres:16-alpine
environment:
POSTGRES_USER: appuser
POSTGRES_DB: appdb
POSTGRES_PASSWORD: LabOnly_PgPass_2026!
db-secure:
image: postgres:16-alpine
environment:
POSTGRES_USER: appuser
POSTGRES_DB: appdb
POSTGRES_PASSWORD_FILE: /run/secrets/db_password
secrets:
- db_password
secrets:
db_password:
file: ./secrets/db_password.txt
Inspecting Config.Env on both containers shows the exposure gap immediately:
1
2
3
# db-insecure: plaintext password sits in container metadata
docker inspect env-secrets-lab-db-insecure-1 \
--format '{{range .Config.Env}}{{println .}}{{end}}' | grep -E '^POSTGRES_' | sort
1
2
3
POSTGRES_DB=appdb
POSTGRES_PASSWORD=LabOnly_PgPass_2026!
POSTGRES_USER=appuser
1
2
3
# db-secure: only the file path appears in Config.Env
docker inspect env-secrets-lab-db-secure-1 \
--format '{{range .Config.Env}}{{println .}}{{end}}' | grep -E '^POSTGRES_' | sort
1
2
3
POSTGRES_DB=appdb
POSTGRES_PASSWORD_FILE=/run/secrets/db_password
POSTGRES_USER=appuser
Inside db-secure, /run/secrets/db_password is mounted with 0600 (-rw-------) permissions and rejects writes with Read-only file system:
1
docker compose exec -T db-secure ls -la /run/secrets/
1
2
3
4
total 16
drwxr-xr-x 2 root root 4096 Dec 5 05:46 .
drwxr-xr-x 2 root root 4096 Dec 5 05:46 ..
-rw------- 1 root root 20 Dec 5 05:46 db_password
To confirm PostgreSQL actually initialized its user password from that file, I connected from a separate container over the Compose network:
1
2
3
4
5
6
7
8
9
# Correct password over the Compose network -> exit code 0
docker compose run --rm --no-deps -e PGPASSWORD="$(cat ./secrets/db_password.txt)" db-secure \
psql -h db-secure -U appuser -d appdb -tAc "SELECT current_user, current_database();"
# appuser|appdb
# Wrong password over the Compose network -> exit code 2
docker compose run --rm --no-deps -e PGPASSWORD="WrongPassword!" db-secure \
psql -h db-secure -U appuser -d appdb -tAc "SELECT 1;"
# psql: error: connection to server at "db-secure" (172.30.0.2), port 5432 failed: FATAL: password authentication failed for user "appuser"
Don’t test PostgreSQL password authentication with
psql -h 127.0.0.1inside thepostgres:16-alpinecontainer itself. Its defaultpg_hba.conftrusts local loopback connections, so even a wrong password succeeds. Always test from another container over the Compose network (-h db-secure).
Standalone Compose secrets limits and when to use each option
The secrets: keyword sounds like encrypted in-memory storage, which is how Docker Swarm delivers secrets over Raft into a tmpfs mount. Standalone (non-Swarm) Docker Compose doesn’t work that way—it mounts the host file as a read-only bind mount.
docker inspect confirms "Type": "bind" and "RW": false:
1
docker inspect env-secrets-lab-db-secure-1 --format '{{json .Mounts}}'
1
2
3
4
5
6
7
8
9
10
[
{
"Type": "bind",
"Source": "/tmp/compose-env-lab/exp3-secrets/secrets/db_password.txt",
"Destination": "/run/secrets/db_password",
"Mode": "",
"RW": false,
"Propagation": "rprivate"
}
]
Checking /proc/mounts inside the container also shows a read-only bind mount rather than tmpfs (VirtioFS fakeowner on macOS Docker Desktop, or the host filesystem on native Linux). File-based Compose secrets keep passwords out of Config.Env and accidental env dumps, but the plaintext file still sits on the host disk.
Use this matrix to pick the right mechanism and know when to avoid each one:
| Mechanism | Primary use | Exposed in docker inspect | When not to use it |
|---|---|---|---|
.env (interpolation) | Image tags, host ports, project-wide variables | Yes, if interpolated into environment | Expecting keys to appear in containers automatically |
env_file | Bulk non-sensitive app settings per environment | Yes | Passwords, API keys, or private tokens |
environment | Small per-service overrides and static flags | Yes | Hardcoding secrets in Git-tracked compose.yaml |
secrets + *_FILE | Database passwords, signing keys, certificates | No (only /run/secrets/ path) | Multi-node production clusters needing encrypted distribution or automated rotation |
Once you need centralized encryption at rest, multi-node secret delivery, or zero-downtime rotation, stop stretching standalone Compose files and move to Docker Swarm encrypted secrets, HashiCorp Vault, or your cloud provider’s secret manager.
Production caveats and checklist
Four practical pitfalls show up repeatedly when teams adopt .env and file-based secrets:
- Committing
.envorsecrets/to Git: Track only.env.exampleand an emptysecrets/.gitkeep, and ignore.envandsecrets/*.txtin.gitignore. - Trailing newlines in secret files: Writing a secret with
echo "secret" > db_password.txtappends\n, which breaks strict authentication checks in many drivers. Useprintf '%s' '...'or strip whitespace in application code. - File permissions with non-root containers: If your service runs as an unprivileged UID—as covered in Isolating Docker containers as non-root and scanning with Trivy—a host file owned by
root:rootwith mode0600causes permission-denied startup failures. Align file ownership or use long-syntaxsecretsoptions (uid,gid,mode). - Sharing
docker compose configoutput: Any${SECRET}interpolated intoenvironment:renders in plaintext when you rundocker compose config. Scrub sensitive fields before pasting the output into tickets or chat.
Pre-deployment checklist
- Keep
.envstrictly forcompose.yamlinterpolation and declareenv_fileexplicitly for container settings. - Guard mandatory variables with
${VAR:?error message}so missing values fail before containers start. - Move passwords and tokens to
secrets+*_FILEand verify they don’t appear indocker inspectConfig.Env. - Lock down host secret files with
chmod 600and confirm.envandsecrets/are listed in.gitignore. - Run
docker compose configbefore deploying to verify mergedenvironmentandenv_filevalues.