patterndockerModerate
Compose environment files (.env) set variables for Compose itself and containers
Viewed 0 times
env file.envenv_fileenvironment variablesvariable substitutioncompose interpolation
Problem
Developers hardcode values in docker-compose.yml or don't understand the difference between the .env file (for Compose variable substitution),
env_file (for container env vars), and environment (explicit key-value pairs).Solution
There are three distinct mechanisms:
.envfile in project root — variables available for${VAR}substitution in docker-compose.yml itselfenv_file:— file whose contents are injected as env vars into the containerenvironment:— explicit env vars in the Compose file
services:
app:
env_file:
- .env.local # injected into container
environment:
NODE_ENV: production # explicit, overrides env_fileWhy
Docker Compose reads .env before parsing the YAML and uses it for variable interpolation. env_file contents go directly into the container environment. Mixing them up causes missing variables or accidental exposure.
Gotchas
- .env is read by Compose for its own interpolation — it's NOT automatically passed to containers unless you use env_file
- env_file: passes all KEY=VALUE lines to the container, including comments-as-env-vars if you use # incorrectly
- environment: values override env_file values for the same key
- Use
--env-fileflag to specify an alternative to .env:docker compose --env-file .env.staging up
Code Snippets
.env file for Compose variable substitution
# .env (for Compose interpolation)
POSTGRES_VERSION=16
APP_IMAGE=myapp
APP_TAG=latestAll three env mechanisms in one Compose file
services:
app:
image: ${APP_IMAGE}:${APP_TAG} # uses .env interpolation
env_file:
- .env.local # ALL vars from this file go into container
environment:
NODE_ENV: production # explicit, wins over env_file
DATABASE_URL: postgres://db:5432/app
db:
image: postgres:${POSTGRES_VERSION}Context
Managing environment configuration across Docker Compose services
Revisions (0)
No revisions yet.