SkillByAIOpen interactive version →

Lesson 9 / 25

Environment Precedence Inside Containers

Which value does the container see?

environment beats env_file

Inside containers, values set with environment in the Compose file take precedence over the same keys from env_file, which take precedence over ENV defaults baked into the image. docker compose run -e KEY=value overrides for a single run. Interpolation (${...}) happens earlier, when the file is loaded. When in doubt, inspect the resolved configuration with docker compose config, or docker compose exec <svc> env in a running container.

Precedence order

Highest first. Check the Compose docs for the full list in your version.

1. docker compose run -e KEY=value          (one-off override)
2. environment: in the Compose file          (values may be interpolated from shell / .env)
3. env_file: files listed for the service
4. ENV in the Dockerfile (image default)

Inspect, do not guess

Run docker compose config (or exec env in a running container) to see the value a service will actually get.

Quick check: A key is in both env_file and environment. Which value does the container get?

  • Neither
  • The value from env_file
  • The value from environment
  • A random one
Answer

The value from environment — Explicit environment wins.