Docker Compose — Environment Key
The environment: key sets environment variables inside the container at runtime.
Map Syntax (Recommended)
services:
api:
image: node:20-alpine
environment:
NODE_ENV: production
PORT: "3000"
DATABASE_URL: postgres://user:pass@db:5432/mydb
List Syntax
services:
api:
image: node:20-alpine
environment:
- NODE_ENV=production
- PORT=3000
- DATABASE_URL=postgres://user:pass@db:5432/mydb
Both syntaxes are equivalent. Map syntax is more readable; list syntax matches docker run -e.
Pass Through Host Variables
If you omit the value, Compose passes through the variable from the host shell:
services:
api:
image: node:20-alpine
environment:
- API_KEY # Passed from host: export API_KEY=abc123
export API_KEY=abc123
docker compose up -d
docker compose exec api printenv API_KEY
abc123
Verify Container Variables
docker compose exec api env | sort
DATABASE_URL=postgres://user:pass@db:5432/mydb
NODE_ENV=production
PORT=3000
When to Use environment:
| Scenario | Recommendation |
|---|---|
| Few variables | Use environment: directly |
| Many variables | Use env_file: instead |
| Secrets | Use Docker secrets (see later) |
| Build-time only | Use args: in build section |
Real-World Analogy
environment: is like setting environment variables in your shell (e.g., export NODE_ENV=production) — they exist for the life of the session (container).
Summary
| Syntax | Example |
|---|---|
| Map | NODE_ENV: production |
| List | - NODE_ENV=production |
| Pass-through | - API_KEY (from host) |
| Verify | docker compose exec <svc> env |
Quick Reference
| Item | Detail |
|---|---|
| Map syntax | KEY: value (recommended) |
| List syntax | - KEY=value |
| Pass-through | - KEY (no value, from host) |
| Verify | docker compose exec |
| Many vars | Use env_file: instead |