Docs / Containers & Docker / Docker Compose for Multi-Service Applications

Docker Compose for Multi-Service Applications

By Admin · Jan 23, 2026 · Updated Apr 23, 2026 · 546 views · 2 min read

What is Docker Compose?

Docker Compose lets you define and run multi-container applications with a single YAML file. Instead of managing each container separately, you describe your entire stack.

Basic Structure

# docker-compose.yml
services:
  web:
    image: nginx:alpine
    ports:
      - "80:80"
    volumes:
      - ./html:/usr/share/nginx/html
    depends_on:
      - app

  app:
    build: .
    environment:
      - DATABASE_URL=postgres://user:pass@db:5432/myapp
    depends_on:
      - db

  db:
    image: postgres:16-alpine
    environment:
      POSTGRES_DB: myapp
      POSTGRES_USER: user
      POSTGRES_PASSWORD: pass
    volumes:
      - pgdata:/var/lib/postgresql/data

volumes:
  pgdata:

Common Commands

Command Description
docker compose up -d Start all services in background
docker compose down Stop and remove containers
docker compose logs -f Follow all logs
docker compose logs -f app Follow specific service logs
docker compose ps List running services
docker compose exec app bash Shell into running container
docker compose build Rebuild images
docker compose pull Pull latest images

Environment Variables

services:
  app:
    env_file:
      - .env
    environment:
      - NODE_ENV=production
      # Reference host env vars
      - API_KEY=${API_KEY}

.env file:

DATABASE_URL=postgres://user:pass@db:5432/myapp
REDIS_URL=redis://cache:6379
SECRET_KEY=your-secret-here

Danger Never commit .env files to version control. Add .env to .gitignore.

Health Checks

services:
  db:
    image: postgres:16-alpine
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U user -d myapp"]
      interval: 10s
      timeout: 5s
      retries: 5

  app:
    build: .
    depends_on:
      db:
        condition: service_healthy

Networking

Services communicate by service name:

# From the "app" service, connect to "db" by name
connection = psycopg2.connect("host=db port=5432 dbname=myapp")

# Connect to "cache" (Redis)
redis = Redis(host="cache", port=6379)

Production Tips

services:
  app:
    restart: unless-stopped
    deploy:
      resources:
        limits:
          cpus: '2.0'
          memory: 512M
    logging:
      driver: json-file
      options:
        max-size: "10m"
        max-file: "3"

Tip Use docker compose up -d --remove-orphans to clean up containers from services you've removed from the compose file.

Was this article helpful?