Docker Compose — Dotenv File
The .env file is a special file that Compose auto-loads for variable substitution in compose.yml itself — NOT directly into containers.
How .env Works
.env file compose.yml
────────── ────────────────────────────
POSTGRES_TAG=16 image: postgres:${POSTGRES_TAG}
API_PORT=3000 ports:
- "${API_PORT}:3000"
The .env file feeds values into ${...} placeholders in compose.yml.
Example
.env:
COMPOSE_PROJECT_NAME=myapp
POSTGRES_TAG=16
API_PORT=3000
REDIS_TAG=7
compose.yml:
services:
db:
image: postgres:${POSTGRES_TAG}
ports:
- "5432:5432"
api:
image: myapi:latest
ports:
- "${API_PORT}:3000"
cache:
image: redis:${REDIS_TAG}
Verify Substitution
docker compose config
This shows the resolved compose file with variables expanded:
services:
db:
image: postgres:16
api:
ports:
- "3000:3000"
cache:
image: redis:7
.env vs env_file
| Feature | .env |
env_file: |
|---|---|---|
| Location | Same directory as compose.yml | Anywhere (path specified) |
| Purpose | Configure compose.yml itself | Set container ENV vars |
| Auto-loaded | Yes | No (must declare) |
| Target | Compose variable substitution | Container environment |
Custom .env File
docker compose --env-file .env.staging up
COMPOSE_PROJECT_NAME
The .env file is the best place to set the project name:
COMPOSE_PROJECT_NAME=myapp
This avoids the project name depending on the directory name.
Security Best Practices
# Always add .env to .gitignore
echo ".env" >> .gitignore
# Commit a template instead
cp .env .env.example
# Remove secret values from .env.example
git add .env.example
Summary
| Aspect | Detail |
|---|---|
| Location | Same directory as compose.yml |
| Purpose | Configure the compose file, not containers |
| Syntax | KEY=value (same as env_file) |
| Verify | docker compose config shows resolved values |
| Custom file | docker compose –env-file .env.prod up |
Quick Reference
| Item | Detail |
|---|---|
| .env file | Auto-loaded for variable substitution |
| Usage | ${VAR_NAME} in compose.yml |
| Verify | docker compose config (shows resolved values) |
| Custom env | docker compose –env-file .env.prod up |
| vs env_file | .env configures Compose; env_file configures containers |
| Security | Add .env to .gitignore, commit .env.example |