Quick answer

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 (.env and --env-file): Substitutes ${VAR} text placeholders inside compose.yaml itself before Docker creates anything. By itself, .env injects zero variables into any container.
  • Phase 2 — Container Runtime Injection (env_file: and environment:): Passes key-value variables into the running container process, and is never consulted to fill ${VAR} placeholders in compose.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.

PropertyProject .env (or CLI --env-file)Service env_file: attribute
When Compose reads itPhase 1: Parsing compose.yamlPhase 2: Creating the container runtime environment
Fills ${VAR} in compose.yaml? (image:, ports:, volumes:)YesNo — 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 directoryResolves from compose.yaml’s parent folder, regardless of your shell pwd
If the file is missingDefault .env: silent no-op; explicit --env-file: hard errorHard error by default (unless required: false on Compose 2.24+)
Visible in docker compose config?Shows interpolated values inside the rendered YAMLExpands 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):

PriorityMechanismExampleCritical edge case to watch
1 (Highest)docker compose run -e CLI flagdocker compose run --rm -e APP_ENV=cli_run web envApplies only to docker compose run one-off containers (docker compose up has no -e flag). Bare -e VAR pulls from host shell.
2Host 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!
3Service environment: attribute in compose.yamlenvironment: [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:.
4Service env_file: attribute in compose.yamlenv_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).
5Container image Dockerfile ENVENV APP_ENV=image_default baked into image layersPure fallback. Evaluates only if Levels 1–4 have zero entry for APP_ENV. Any Compose entry replaces it completely.
6 (Lowest)Unset / undefinedVariable omitted everywhereAbsent 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:

  1. Host OS shell environment (export VAR=... or inline VAR=... docker compose ...)
  2. CLI --env-file file(s) (or COMPOSE_ENV_FILES; if passed multiple times, the last --env-file wins)
  3. Default .env file in the project directory (unless disabled via COMPOSE_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:

  • image resolved to alpine:3.20, while IMAGE_TAG itself is absent from environment: (proving .env alone stays out of the container).
  • TEST_FILE_ONLY equals FROM_ENV_FILE (Level 4).
  • TEST_CONFLICT equals FROM_COMPOSE_ENV (Level 3 beat Level 4).
  • TEST_SHELL_BRIDGE equals FROM_DOTENV (.env interpolated ${TEST_INTERPOLATED} into Level 3).
  • TEST_EMPTY_TRAP equals "" (an empty string in Level 3 wiped out GOOD_VALUE_IN_ENV_FILE from 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:

SyntaxVariable is unsetVariable is empty (VAR=)Variable is VAR=customBest 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 msgFails 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:

  1. .env shapes compose.yaml only: Pinned image versions (IMMICH_VERSION), published host ports, and host bind-mount paths (UPLOAD_LOCATION) live in .env, guarded by :- defaults or :? checks.
  2. env_file: feeds application config: App-internal flags go into a dedicated ./app.env (with chmod 600), while actual credentials use /run/secrets/ _FILE mounts wherever supported.
  3. Never define the same variable name in both environment: and env_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

Frequently asked questions

Does a .env file automatically set variables in my container?
No. Docker’s official precedence documentation notes that the Host OS environment and .env file columns do not place variables into a container on their own. A project .env file only feeds ${VAR} interpolation inside compose.yaml. To inject variables into a running container, declare them under environment: or env_file:.
What is the difference between .env and env_file?
They operate at two different phases and point in opposite directions. The project .env file feeds YAML interpolation while Compose parses compose.yaml (such as image: postgres:${PG_MAJOR}). The service env_file: attribute injects key-value pairs into the container process at runtime and is completely ignored during YAML interpolation.
What is the 6-level precedence order for environment variables in Docker Compose?
From highest to lowest inside the container: (1) docker compose run -e on the CLI, (2) host shell environment variables passed through or interpolated via environment:/env_file:, (3) explicit values under the service environment: attribute, (4) files listed under the service env_file: attribute, (5) Dockerfile ENV defaults in the image, and (6) unset.
Does environment beat env_file when empty?
Yes. Docker’s precedence specification states that environment: overrides env_file: even when the value under environment: is empty or undefined. Writing API_URL= or API_URL: ${UNSET_VAR} under environment: silently wipes out a working API_URL defined inside your env_file.
Why did my image tag fail with invalid reference format?
Because an unset ${VAR} placeholder during YAML interpolation evaluates to an empty string rather than stopping with an error. Writing image: postgres:${POSTGRES_VERSION} when POSTGRES_VERSION is missing turns into postgres:, which Docker rejects downstream as an invalid image reference. Guard required tags with ${POSTGRES_VERSION:?Set POSTGRES_VERSION} or ${POSTGRES_VERSION:-17}.
When does a Dockerfile ENV apply?
Only as a fallback when Compose says nothing about that variable. Any entry for that variable name via docker compose run -e, environment:, or env_file: replaces the Dockerfile ENV value completely.
Should I put database passwords in environment variables?
Avoid it whenever the image supports file secrets. Container environment variables are exposed in plaintext to docker inspect and anyone with Docker socket access. Mount Compose secrets at /run/secrets/ and pass the path via variables like POSTGRES_PASSWORD_FILE instead.
Why does a missing –env-file error out while a missing .env stays silent?
An explicit –env-file path on the command line is a mandatory contract, so Compose exits with an error if the file is absent. The default .env next to compose.yaml is optional by design, so cloning a repo onto a new host without copying .env silently leaves every ${VAR} blank.

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.

About the author

Written by Lowell K. Wood IV, who builds and runs TechFuelHQ from St. Louis, Missouri.