Docker Compose Spec Cheat Sheet

Quick reference guide for Docker Compose: Specification format, service definitions, volume/network mounts, and CLI.

Containers & Cloud
docker
docker-compose
containers

Docker Compose is a tool for defining and running multi-container Docker applications using a declarative Compose specification YAML file.

`compose.yaml` Structure Example

yaml
name: my-app-stack

services:
  web:
    build:
      context: .
      dockerfile: Dockerfile
    ports:
      - "3000:3000"
    environment:
      NODE_ENV: production
      DATABASE_URL: postgres://user:pass@db:5432/appdb
    depends_on:
      db:
        condition: service_healthy
    restart: unless-stopped

  db:
    image: postgres:16-alpine
    environment:
      POSTGRES_USER: user
      POSTGRES_PASSWORD: pass
      POSTGRES_DB: appdb
    ports:
      - "5432:5432"
    volumes:
      - pgdata:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U user -d appdb"]
      interval: 10s
      timeout: 5s
      retries: 5

volumes:
  pgdata:

Service Directives Key Reference

Table
DirectivePurposeExample Value
imageSpecify pre-built Docker hub imageimage: redis:7-alpine
buildBuild image from Dockerfile pathbuild: { context: ./app }
portsMap host port to container portports: ["8080:80"]
environmentSet container environment variablesenvironment: [DEBUG=true]
env_fileImport env variables from fileenv_file: [.env.production]
volumesMount host directory or named volumevolumes: ["./data:/app/data"]
restartContainer restart policyrestart: unless-stopped

Essential `docker compose` CLI v2 Commands

Table
CommandPurpose / Action
docker compose up -dBuild, create, and start containers in background
docker compose downStop containers and remove networks created by up
docker compose down -vStop containers AND delete persistent named volumes
docker compose psList status of all running stack containers
docker compose logs -f webFollow real-time log output for service
docker compose exec web shExecute interactive shell command inside container
docker compose build --no-cacheForce rebuild of service image without build cache

Common Pitfalls & Tips

[!WARNING] Use docker compose (with space, CLI v2 plugin) instead of deprecated docker-compose (with hyphen, Python v1 CLI).

[!TIP] Always quote port bindings like "80:80" in YAML to prevent YAML parsers from converting 60:60 into sexagesimal base-60 integers!