Back to Home
Docker
Multi-service application with Docker Compose: networks, healthchecks, volumes and environment management
composenetworkhealthcheckvolumesenvironmentmulti-servicenginxredis
Docker Compose - Intermediate
Real-world Docker Compose configuration for multi-service applications.
Full Application Example
services:
nginx:
image: nginx:alpine
ports:
- "80:80"
- "443:443"
volumes:
- ./nginx/nginx.conf:/etc/nginx/nginx.conf:ro
- ./nginx/certs:/etc/nginx/certs:ro
depends_on:
backend:
condition: service_healthy
networks:
- frontend
restart: unless-stopped
backend:
build:
context: ./backend
dockerfile: Dockerfile
args:
- NODE_ENV=production
env_file:
- .env
environment:
- DATABASE_URL=postgres://user:pass@db:5432/myapp
- REDIS_URL=redis://redis:6379
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:3000/health"]
interval: 30s
timeout: 10s
retries: 3
start_period: 40s
depends_on:
db:
condition: service_healthy
redis:
condition: service_started
networks:
- frontend
- backend
restart: unless-stopped
db:
image: postgres:16-alpine
environment:
POSTGRES_USER: user
POSTGRES_PASSWORD: pass
POSTGRES_DB: myapp
volumes:
- postgres_data:/var/lib/postgresql/data
- ./init.sql:/docker-entrypoint-initdb.d/init.sql
healthcheck:
test: ["CMD-SHELL", "pg_isready -U user -d myapp"]
interval: 10s
timeout: 5s
retries: 5
networks:
- backend
restart: unless-stopped
redis:
image: redis:7-alpine
command: redis-server --appendonly yes --maxmemory 256mb
volumes:
- redis_data:/data
networks:
- backend
restart: unless-stopped
networks:
frontend:
driver: bridge
backend:
driver: bridge
internal: true
volumes:
postgres_data:
redis_data:
Network Isolation
networks:
frontend:
driver: bridge
backend:
driver: bridge
internal: true
- frontend: accessible by nginx and backend
- backend: accessible by db, redis and backend only, no external access
Healthcheck Configuration
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:3000/health"]
interval: 30s
timeout: 10s
retries: 3
start_period: 40s
Environment Management
# .env file
DATABASE_URL=postgres://user:pass@db:5432/myapp
REDIS_URL=redis://redis:6379
JWT_SECRET=my-secret-key
services:
backend:
env_file:
- .env
- .env.local
environment:
- NODE_ENV=production
Useful Compose Commands
docker compose up -d --build backend
docker compose logs -f backend db
docker compose ps
docker compose exec db psql -U user -d myapp
docker compose down -v --remove-orphans
docker compose up -d db redis