Docker Compose Basic Structure
YAML
# docker-compose.yml
version: "3.9"
services:
app:
build:
context: .
dockerfile: Dockerfile.dev
ports:
- "3000:3000"
volumes:
- .:/app
- /app/node_modules # Protect container node_modules
environment:
- NODE_ENV=development
depends_on:
db:
condition: service_healthy
db:
image: postgres:16-alpine
environment:
POSTGRES_USER: dev
POSTGRES_PASSWORD: devpass
POSTGRES_DB: myapp
volumes:
- pg_data:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U dev"]
interval: 5s
timeout: 3s
retries: 5
redis:
image: redis:7-alpine
command: redis-server --save 60 1
volumes:
pg_data:Commonly Used Compose Commands
Bash
docker compose up -d # Run in the background
docker compose up --build # Rebuild images, then start
docker compose down -v # Remove containers and volumes
docker compose logs -f app # Follow logs for a specific service
docker compose exec app bash # Open a shell in the container
docker compose ps # Check service statusSeparating Environment Variable Files
Bash
# .env (exclude from git)
DB_PASSWORD=secretpass
API_KEY=abc123
# docker-compose.yml
services:
app:
env_file:
- .envSeparating Development and Production Configs
Bash
# docker-compose.override.yml (for development; can be excluded from git)
services:
app:
volumes:
- .:/app
command: npm run devBash
docker compose -f docker-compose.yml -f docker-compose.prod.yml up -dEditorial note
AI tools may assist drafting. Check the evidence in each guide for whether commands were run and which environment was used. Confirm the current docs for your version before applying instructions, and email us about errors. email us
Topic-related official docs (auto-linked · not per-claim sources)Docker documentation ↗
Questions & answers
Ask a question about this guide. We'll review and reply.