Docker_compose
Chapter 08: Docker Compose
Section titled “Chapter 08: Docker Compose”Docker Compose is a tool for defining and running multi-container Docker applications. With Compose, you use a YAML file to configure your application’s services.
Why Docker Compose?
Section titled “Why Docker Compose?”When applications need multiple containers (web app, database, cache, queue), managing them individually becomes complex:
┌─────────────────────────────────────────────────────────────────────────────┐│ Without vs With Docker Compose │├─────────────────────────────────────────────────────────────────────────────┤│ ││ Without Compose: With Compose: ││ ┌─────────────────┐ ┌─────────────────┐ ││ │ docker run -d │ │ docker-compose │ ││ │ --name web ... │ │ up -d │ ││ │ docker run -d │ └────────┬────────┘ ││ │ --name db ... │ │ ││ │ docker run -d │ │ ││ │ --name redis... │ │ ││ │ docker run -d │ │ ││ │ --name worker.. │ │ ││ └─────────────────┘ ▼ ││ ┌─────────────────┐ ││ │ docker-compose │ ││ │ .yml │ ││ └─────────────────┘ ││ │└─────────────────────────────────────────────────────────────────────────────┘Docker Compose File
Section titled “Docker Compose File”Basic Example
Section titled “Basic Example”version: '3.8'
services: web: image: nginx:latest ports: - "8080:80"
api: image: myapi:latest depends_on: - db environment: - DATABASE_URL=postgres://db:5432/mydb
db: image: postgres:15 environment: - POSTGRES_PASSWORD=secret - POSTGRES_DB=mydb volumes: - db-data:/var/lib/postgresql/data
volumes: db-data:Version
Section titled “Version”# Use version '3' for Docker Engine 17.12.0+# Use version '3.8' for newer featuresversion: '3.8'Service Configuration
Section titled “Service Configuration”services: web: image: nginx:1.25 # Or build from Dockerfile build: . # Or build with context and dockerfile build: context: ./dir dockerfile: Dockerfileservices: web: ports: # Short syntax - "8080:80" - "8443:443"
# Long syntax - target: 8080 host: 0.0.0.0 protocol: tcpEnvironment Variables
Section titled “Environment Variables”services: api: environment: # Short syntax - NODE_ENV=production - DATABASE_URL=postgres://db:5432/mydb
# Long syntax - name: NODE_ENV value: productionVolumes
Section titled “Volumes”services: web: volumes: # Short syntax - ./html:/usr/share/nginx/html:ro - nginx-data:/var/log/nginx
# Long syntax - type: volume source: nginx-data target: /var/log/nginx read_only: trueNetworks
Section titled “Networks”services: web: networks: - frontend - backend
networks: frontend: driver: bridge backend: driver: bridgeDependencies (depends_on)
Section titled “Dependencies (depends_on)”services: web: depends_on: - db - redis
db: image: postgres:15
redis: image: redis:7Commands
Section titled “Commands”Starting Services
Section titled “Starting Services”# Start all services (detached mode)docker-compose up -d
# Start specific servicedocker-compose up -d web
# Start with builddocker-compose up --build
# Recreate containersdocker-compose up -d --force-recreateManaging Services
Section titled “Managing Services”# Stop servicesdocker-compose stop
# Stop and remove containersdocker-compose down
# Remove volumes toodocker-compose down -v
# Remove imagesdocker-compose down --rmi local
# View logsdocker-compose logs -f
# View logs for specific servicedocker-compose logs -f webExecuting Commands
Section titled “Executing Commands”# Run command in servicedocker-compose exec web sh
# Run one-off commanddocker-compose run --rm web npm testScaling
Section titled “Scaling”# Scale servicedocker-compose up -d --scale web=3
# Note: Requires proper load balancing setupConfiguration
Section titled “Configuration”# Validate configurationdocker-compose config
# List containersdocker-compose ps
# Pull imagesdocker-compose pullAdvanced Features
Section titled “Advanced Features”Health Checks
Section titled “Health Checks”services: db: image: postgres:15 healthcheck: test: ["CMD-SHELL", "pg_isready -U postgres"] interval: 10s timeout: 5s retries: 5Resource Limits
Section titled “Resource Limits”services: web: deploy: resources: limits: cpus: '0.5' memory: 512M reservations: cpus: '0.25' memory: 256MSecrets
Section titled “Secrets”services: db: image: postgres:15 secrets: - db_password
secrets: db_password: file: ./db_password.txtProfiles
Section titled “Profiles”services: web: image: nginx
monitor: image: prometheus profiles: - monitoringRun with profile:
docker-compose --profile monitoring upEnvironment Files
Section titled “Environment Files”# .env fileCOMPOSE_PROJECT_NAME=myappPOSTGRES_PASSWORD=secret
# docker-compose.ymlservices: db: image: postgres:15 environment: POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}Multi-Environment Configuration
Section titled “Multi-Environment Configuration”Override Files
Section titled “Override Files”# File structuredocker-compose.yml # Base configdocker-compose.override.yml # Local overridesdocker-compose.prod.yml # Production overridesservices: web: image: myapp:latest environment: - ENV=development
# docker-compose.override.yml (auto-loaded)services: web: ports: - "3000:3000" volumes: - .:/appservices: web: image: myapp:v1.0 restart: always ports: - "80:80"Using Override Files
Section titled “Using Override Files”# Development (uses override automatically)docker-compose up -d
# Productiondocker-compose -f docker-compose.yml -f docker-compose.prod.yml up -dComplete Example
Section titled “Complete Example”version: '3.8'
services: # Reverse Proxy nginx: image: nginx:alpine ports: - "80:80" - "443:443" volumes: - ./nginx.conf:/etc/nginx/nginx.conf:ro depends_on: - web networks: - frontend
# Web Application web: build: . environment: - DATABASE_URL=postgresql://user:password@db:5432/mydb - REDIS_URL=redis://redis:6379 depends_on: db: condition: service_healthy redis: condition: service_started networks: - frontend - backend
# Database db: image: postgres:15 environment: - POSTGRES_USER=user - POSTGRES_PASSWORD=password - POSTGRES_DB=mydb volumes: - db-data:/var/lib/postgresql/data healthcheck: test: ["CMD-SHELL", "pg_isready -U user -d mydb"] interval: 10s timeout: 5s retries: 5 networks: - backend
# Cache redis: image: redis:7-alpine networks: - backend
# Background Worker worker: build: . command: npm run worker environment: - DATABASE_URL=postgresql://user:password@db:5432/mydb - REDIS_URL=redis://redis:6379 depends_on: - db - redis networks: - backend
networks: frontend: backend:
volumes: db-data:Summary
Section titled “Summary”In this chapter, you learned:
- What Docker Compose is and why to use it
- Writing docker-compose.yml files
- Service configuration options
- Docker Compose commands
- Advanced features (health checks, secrets, profiles)