Docker ComposeLesson 4.3
Docker Compose environment variables and .env files
.env file, variable substitution, environment block, env_file, docker compose config, secrets management, .env.example
Managing Configuration Across Environments
Hard-coding secrets in a Compose file is a security risk. Compose supports two clean patterns for injecting config.
Pattern 1: .env File Substitution
Compose automatically loads .env from the same directory. Variables defined there can be referenced in the Compose file using ${VAR}.
# .env
DB_PASSWORD=supersecret
DB_NAME=appdb
API_PORT=3000
# docker-compose.yml
services:
api:
ports:
- "${API_PORT}:3000"
db:
environment:
POSTGRES_PASSWORD: ${DB_PASSWORD}
POSTGRES_DB: ${DB_NAME}Pattern 2: env_file per Service
services:
api:
env_file:
- .env.apiThis loads all variables from the file directly into the container environment without needing individual environment entries.
Verify Substitution
docker compose config
This prints the resolved Compose file with all variables substituted — useful for debugging. Always commit a .env.example with placeholder values and add .env to .gitignore. Never commit real credentials.
