Cloud Native › Compose

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.

Docker Compose environment precedence and file-based secrets

A .env file in your project root only interpolates compose.yaml—it doesn’t inject variables into running containers. This post verifies Docker Compose’s two-stage precedence across .env, env_file, and environment, then compares secrets with *_FILE injection 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.21 and postgres:16-alpine containers on Docker Engine 29.9.3 and Docker 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):

VariableDefault run--env-file custom.envAPP_MODE=from_shellWinning layer
IMAGE_ONLYfrom_imagefrom_imagefrom_imageDockerfile ENV
ENV_FILE_ORDERfrom_env_file_2from_env_file_2from_env_file_2env_file (later file wins)
LOG_LEVELfrom_env_file_2from_env_file_2from_env_file_2env_file (unreferenced in YAML)
DB_HOSTfrom_environmentfrom_environmentfrom_environmentenvironment literal
APP_MODEfrom_dotenvfrom_custom_env_filefrom_shellInterpolation (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:

  1. YAML interpolation order: shell environment > --env-file > root .env. Passing --env-file replaces the default .env file rather than merging with it.
  2. Container injection order: environment > env_file (last file wins) > Dockerfile ENV. Both mapping syntax (APP_MODE: ${APP_MODE}) and passthrough list syntax (- APP_MODE in app-list) follow the exact same interpolation precedence.
  3. Unreferenced .env keys never override env_file: Even though .env sets LOG_LEVEL=from_dotenv, compose.yaml never references ${LOG_LEVEL}, so override.env keeps from_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}
SyntaxWhen unsetWhen empty (VAR="")Best fit
${VAR:-default}defaultdefaultPorts, 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.1 inside the postgres:16-alpine container itself. Its default pg_hba.conf trusts 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:

MechanismPrimary useExposed in docker inspectWhen not to use it
.env (interpolation)Image tags, host ports, project-wide variablesYes, if interpolated into environmentExpecting keys to appear in containers automatically
env_fileBulk non-sensitive app settings per environmentYesPasswords, API keys, or private tokens
environmentSmall per-service overrides and static flagsYesHardcoding secrets in Git-tracked compose.yaml
secrets + *_FILEDatabase passwords, signing keys, certificatesNo (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:

  1. Committing .env or secrets/ to Git: Track only .env.example and an empty secrets/.gitkeep, and ignore .env and secrets/*.txt in .gitignore.
  2. Trailing newlines in secret files: Writing a secret with echo "secret" > db_password.txt appends \n, which breaks strict authentication checks in many drivers. Use printf '%s' '...' or strip whitespace in application code.
  3. 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:root with mode 0600 causes permission-denied startup failures. Align file ownership or use long-syntax secrets options (uid, gid, mode).
  4. Sharing docker compose config output: Any ${SECRET} interpolated into environment: renders in plaintext when you run docker compose config. Scrub sensitive fields before pasting the output into tickets or chat.

Pre-deployment checklist

  • Keep .env strictly for compose.yaml interpolation and declare env_file explicitly for container settings.
  • Guard mandatory variables with ${VAR:?error message} so missing values fail before containers start.
  • Move passwords and tokens to secrets + *_FILE and verify they don’t appear in docker inspect Config.Env.
  • Lock down host secret files with chmod 600 and confirm .env and secrets/ are listed in .gitignore.
  • Run docker compose config before deploying to verify merged environment and env_file values.

References

How to set, use, and manage variables in your Compose file with interpolation
Learn how to securely manage runtime and build-time secrets in Docker Compose.
This post is licensed under CC BY 4.0 by the author.