Environment Variables and .env Files
Configure Compose services cleanly using environment variables, variable substitution, and a .env file so one Compose file works across dev, staging, and prod.
Why Externalize Config?
Hard-coding passwords and ports inside a Compose file is brittle and unsafe. Environment variables let you change behaviour per environment without editing the YAML.
- Keep secrets out of version control
- Reuse one Compose file everywhere
- Override values at runtime
The environment Key
Inside a service declare variables under environment as a map. These are injected into the container at start.
services:
db:
image: postgres:16
environment:
POSTGRES_USER: app
POSTGRES_PASSWORD: secretAll lessons in this course
- What is Docker Compose?
- Writing a Compose File
- Deploying Multi-Service Apps
- Environment Variables and .env Files