PREP WITH PROOF
Menu
DEVOPS & CONTAINERS / PRACTICAL GUIDE

Docker Compose Environment Variables: .env vs env_file

Separate Compose interpolation from container environment precedence. Diagnose .env, --env-file, environment, env_file, empty values and dollar-sign expansion.

THE QUICK ANSWER

Compose first resolves variables such as ${APP_MODE} in its application model, then builds each container’s environment from explicit service settings and other sources. A .env file or CLI --env-file supplies interpolation inputs; a service env_file supplies container variables. The same filename can participate in either role, but those roles are not interchangeable.

Trace the variable through two separate decisions

You edit .env, restart a service, and the application still reads the old value. Or a value appears in the shell but never reaches the container. These symptoms are easier to diagnose when you stop treating every environment-related file as one combined source.

The first decision happens while Compose reads the model: what should an expression such as ${APP_MODE:-development} become? The second decision concerns the container: which variables should its process receive? A value can influence the image tag without becoming a container variable. It can also reach a container through service env_file without being the source for a Compose YAML expression.

This guide targets the modern docker compose CLI. Its small examples use nonsecret labels so the result is safe to inspect. Docker is unavailable in the editorial runtime: the YAML was parsed and shell syntax checked, but Compose rendering, image pulls and container execution were not performed. Expected values below follow the linked official documentation rather than a claimed local Docker test.

MechanismPrimary roleDoes it automatically populate every container?
Host shell variableInput available to Compose interpolationNo; reference or pass it deliberately
Project .env / CLI --env-fileInputs for resolving the Compose modelNo
Service env_fileVariables for that service’s containerYes, for that service, subject to overrides
Service environmentExplicit container environment configurationYes, for that service
compose run -e KEY=valueOverride for a one-off containerOnly that run

Resolve the model before inspecting the container

For interpolation, the shell has priority over file-provided values. An explicit --env-file makes the intended input file easier to identify, but it does not suppress an exported shell variable of the same name. Record the exact command, working directory, Compose file arguments and relevant exported variables when two machines produce different configurations.

The default .env lookup is tied to Compose’s project and invocation rules. Relative paths and a different -f or project directory can change which files matter. For a diagnostic fixture, keep the files together and use an explicit --env-file. Do not assume a file is loaded merely because its name ends in .env.

Use docker compose config --environment to inspect interpolation inputs, and docker compose config to inspect the resulting application model. The first answers what values Compose had available for substitution; it is not a dump of the final environment of a running process. Both outputs can contain sensitive values in a real project, so inspect a narrow synthetic case before sharing logs.

Source: Docker: interpolation inputs and --env-file ↗

Build a fixture where the sources deliberately disagree

Create a new disposable directory with the three files below. Save the YAML as compose.yaml. It defines one service, no published ports and no volumes. The image tag is an illustrative lab choice; pulling and running it still requires a working Docker installation and registry access.

The service reads service.env for container variables. Its environment mapping then explicitly assigns MODE using interpolation from APP_MODE. These names are intentionally different so you can see the source variable and the destination variable separately. FEATURE comes only from the service-level file.

The command invokes sh explicitly. Compose command values do not automatically imply shell interpretation. The doubled dollar signs defer variable expansion to that shell inside the container; this is distinct from interpolating APP_MODE into the service environment mapping.

services:
  lab:
    image: alpine:3.22
    env_file:
      - ./service.env
    environment:
      MODE: "${APP_MODE:-development}"
    command:
      - sh
      - -c
      - 'printf "MODE=%s FEATURE=%s\n" "$$MODE" "$$FEATURE"'

Source: Docker Compose interpolation syntax ↗

Name each file by its role

Save APP_MODE=dotenv in .env. Save the two other assignments shown below in service.env. These are plain demonstration values, not credentials. The .env file participates in interpolation when selected by --env-file; service.env participates because the service explicitly references it.

With APP_MODE absent from the host environment, the resolved MODE is expected to be dotenv, overriding MODE=service-file. FEATURE remains enabled. Merely having APP_MODE in .env does not also create APP_MODE inside the container: this YAML only passes its value into a variable named MODE.

If your application expects APP_MODE instead, either name the destination APP_MODE explicitly or change the application contract. A surprising missing variable can be a naming mismatch rather than a precedence problem. Trace the name the process reads, not only the name used by a deployment script.

# .env
APP_MODE=dotenv

# service.env
MODE=service-file
FEATURE=enabled

Compare a clean invocation with a shell override

The following POSIX-shell commands use env -u to remove only APP_MODE from that command’s inherited environment. This avoids silently testing with an old export. Run them from the disposable directory. The config commands inspect configuration; run creates a temporary one-off container and removes it after exit.

The first run is expected to print MODE=dotenv FEATURE=enabled. The second sets APP_MODE for that invocation, so MODE becomes shell. The final run sets MODE directly with -e and should produce MODE=cli FEATURE=enabled. That CLI override belongs to the new one-off container; it does not update a long-running service container.

If config does not match the expected values, resolve the input and file-selection issue before pulling images or restarting services. If config matches but the application differs, move the investigation to the actual container, startup script and application configuration precedence.

env -u APP_MODE docker compose --env-file .env config --environment
env -u APP_MODE docker compose --env-file .env config

env -u APP_MODE docker compose --env-file .env run --rm lab
APP_MODE=shell docker compose --env-file .env run --rm lab
env -u APP_MODE docker compose --env-file .env run --rm -e MODE=cli lab

Source: Docker Compose config reference ↗

Interpret overrides at the container layer

For explicit assignments in this fixture, service environment overrides the same name from service env_file. The file does not win because it was read from disk later in your mental model. If multiple service env_file entries assign a variable, their listed order matters: a later file overrides an earlier file for that name.

An explicit empty environment value can override a nonempty file value. Do not remove a protective default or assume the file value will reappear just because the override looks blank. A bare key without a value has different resolution behavior again; use explicit values in a reproducible diagnostic case.

Image ENV defaults are a lower-level fallback for names not overridden by Compose’s environment configuration. Dockerfile ARG is a build-time input and does not, by itself, establish a runtime process variable. When tracing a real application, list image defaults separately from the values supplied when the container was created.

Docker’s full precedence reference also covers interpolated and pass-through values. Avoid flattening every source into a slogan such as “the shell always wins.” The shell can win interpolation for a referenced name, yet an unrelated literal service environment assignment still sets its destination value. Ask which name is being resolved and at which stage.

Source: Docker: container environment precedence ↗

Treat empty and missing as different inputs

${NAME:-fallback} uses the fallback when NAME is missing or empty. ${NAME-fallback} uses it only when NAME is missing. In the fixture, APP_MODE= is therefore expected to select development, because the YAML uses the colon form. This is an intentional expression rule, not a mysterious failure to read the shell.

Use ${NAME:?message} when missing or empty input should stop interpolation, or ${NAME?message} when an empty value is allowed but missing input is not. These checks validate configuration presence; they do not verify that a database is reachable or a credential is valid.

Quote string-like environment values in YAML, especially values resembling booleans. Also distinguish a literal dollar sign from a Compose expression. Double-dollar escaping defers expansion, but it does not create a shell: the explicit sh -c in the fixture is what interprets the resulting variable references at process runtime.

Source: Docker Compose interpolation syntax ↗

Inspect the container you actually deployed

A rendered model describes intended configuration, not proof that an existing container was created from it. Confirm the project and service you are inspecting. A different project name, directory or Compose file can leave you looking at another instance while editing the correct-looking file.

docker compose restart does not apply changed environment configuration from the Compose model. Use the appropriate reviewed up/recreation workflow for your service, accounting for dependencies and availability requirements. A one-off compose run may demonstrate the new configuration while the already-running service retains the old environment.

Even the correct process environment may not be the application’s final setting. Startup scripts can transform values, and application config files or command-line flags can override them. Inspect only the relevant nonsecret names and follow the value through the entrypoint and application startup path. Rebuilding the image is not automatically the solution to a runtime configuration mismatch.

Source: Docker Compose restart reference ↗

Keep diagnostics useful without turning config into a secret dump

Use artificial values to reproduce precedence. Avoid posting complete config, inspect or environment output from a production service. A file excluded from source control can still leak through terminal output, CI artifacts, container inspection or screenshots.

For sensitive application inputs, evaluate Compose secrets support and whether the application can read the supplied secret file. Declaring a secret does not automatically rewrite an application that only reads an environment variable. Keep the integration contract explicit and scope each service’s access to what it needs.

The shortest reliable investigation follows one variable across three observations: interpolation inputs, resolved service configuration and the specific container/application instance. Once those agree, preserve a small synthetic regression fixture. That gives future maintainers a clear answer to which source controls the value without relying on repeated restarts or guessed precedence.

Source: Docker: managing secrets in Compose ↗

KEEP THESE THREE THINGS

Your next steps

  1. Identify which layer is wrong: interpolation inputs, the resolved service model, or the environment of an existing container.
  2. Use explicit nonsecret fixtures and config inspection to trace each variable; distinguish empty from unset and host expansion from container expansion.
  3. Apply reviewed configuration through the appropriate recreation workflow; use secrets support for sensitive values rather than publishing resolved environments.

Sources & official resources

Linked resources checked on 2026-10-25. Technical behavior and provider guidance can change; check the documentation for the version you use.

About this guide and its recommendations

Published by Prep With Proof with AI-assisted drafting. Study routines and examples are editorial suggestions, not official exam instructions or claims of a learner's personal results. Cited provider facts are linked; ownership of recommended Prep With Proof products is disclosed. No competitor endorsement or guaranteed certification outcome is implied.

Suggest a correction →