Docker Compose Cheatsheet

A comprehensive reference for Docker Compose configuration and commands. Docker Compose is a tool for defining and running multi-container Docker applications using a YAML file. This cheatsheet covers services, volumes, networks, environment variables, healthchecks, and CLI commands.

127 items
CLI Commands

Basic Commands

docker compose up

Create and start containers

docker compose up -d

Start in detached mode (background)

docker compose up --build

Build images before starting

docker compose down

Stop and remove containers, networks

docker compose down -v

Also remove volumes

docker compose down --rmi all

Also remove images

CLI Commands

Service Management

docker compose start

Start existing containers

docker compose stop

Stop running containers

docker compose restart

Restart containers

docker compose pause

Pause containers

docker compose unpause

Unpause containers

docker compose kill

Force stop containers

CLI Commands

Information

docker compose ps

List containers

docker compose ps -a

List all containers (including stopped)

docker compose logs

View output from containers

docker compose logs -f

Follow log output

docker compose logs service_name

Logs for specific service

docker compose top

Display running processes

docker compose events

Receive real-time events

CLI Commands

Execution

docker compose exec service_name sh

Execute shell in container

docker compose exec service_name command

Execute command in container

docker compose run service_name command

Run one-off command

docker compose run --rm service_name sh

Run and remove after exit

CLI Commands

Build & Images

docker compose build

Build or rebuild services

docker compose build --no-cache

Build without cache

docker compose pull

Pull service images

docker compose push

Push service images

docker compose images

List images used by services

CLI Commands

Configuration

docker compose config

Validate and view config

docker compose config --services

List service names

docker compose config --volumes

List volume names

docker compose version

Show version information

docker compose -f custom.yml up

Use custom compose file

Services

Image & Build

image: ubuntu:22.04

Use specific image

image: nginx:latest

Use latest tag

image: myregistry.com/app:v1

Use private registry image

build: .

Build from Dockerfile in current dir

build:
  context: ./dir
  dockerfile: Dockerfile.dev

Custom build context and Dockerfile

build:
  args:
    - APP_ENV=production

Build arguments

Services

Ports

ports:
  - "3000"

Expose port (random host port)

ports:
  - "8080:80"

Map host:container port

ports:
  - "127.0.0.1:8080:80"

Bind to specific interface

ports:
  - "8080-8090:80-90"

Port range mapping

expose:
  - "3000"

Expose to linked services only

💡 Use quotes for ports to avoid YAML parsing issues

Services

Command & Entrypoint

command: npm start

Override default command

command: ["npm", "start"]

Command as array

command: >
  sh -c 'echo hello &&
  npm start'

Multi-line command

entrypoint: /app/start.sh

Override entrypoint

entrypoint: ["/app/start.sh"]

Entrypoint as array

working_dir: /app

Set working directory

Services

Container Options

container_name: my-app

Custom container name

hostname: myhost

Set container hostname

restart: always

Always restart

restart: unless-stopped

Restart unless manually stopped

restart: on-failure

Restart only on failure

restart: "no"

Never restart (default)

Services

User & Permissions

user: root

Run as root user

user: "1000:1000"

Run as specific UID:GID

user: node

Run as named user

privileged: true

Run in privileged mode

read_only: true

Read-only root filesystem

Volumes

Volume Types

volumes:
  - /var/lib/data

Anonymous volume

volumes:
  - ./host/path:/container/path

Bind mount (host path)

volumes:
  - mydata:/var/lib/data

Named volume

volumes:
  - ./config:/app/config:ro

Read-only mount

volumes:
  - type: bind
    source: ./data
    target: /data

Long syntax

Volumes

Named Volumes

volumes:
  mydata:

Define named volume

volumes:
  mydata:
    driver: local

With driver

volumes:
  mydata:
    external: true

Use existing volume

volumes:
  mydata:
    name: my-custom-name

Custom volume name

💡 Named volumes persist data even when containers are removed

Volumes

Volume Options

volumes:
  - type: volume
    source: mydata
    target: /data
    volume:
      nocopy: true

Don't copy data from container

volumes:
  - type: tmpfs
    target: /tmp
    tmpfs:
      size: 100000000

tmpfs mount with size limit

Networks

Network Configuration

networks:
  frontend:

Define custom network

networks:
  frontend:
    driver: bridge

Bridge network (default)

networks:
  backend:
    driver: overlay

Overlay network (Swarm)

networks:
  mynet:
    external: true

Use existing network

networks:
  mynet:
    name: my-custom-network

Custom network name

Networks

Service Networks

services:
  web:
    networks:
      - frontend
      - backend

Connect to multiple networks

services:
  web:
    networks:
      frontend:
        aliases:
          - webapp

Network alias

services:
  web:
    networks:
      frontend:
        ipv4_address: 172.16.0.10

Static IP address

services:
  web:
    network_mode: host

Use host network

services:
  web:
    network_mode: "service:other"

Share network with service

Networks

Network Options

networks:
  mynet:
    ipam:
      config:
        - subnet: 172.28.0.0/16

Custom subnet

networks:
  mynet:
    internal: true

Internal network (no external access)

networks:
  mynet:
    attachable: true

Allow manual container attachment

Environment

Environment Variables

environment:
  - NODE_ENV=production

Array syntax

environment:
  NODE_ENV: production
  DEBUG: "true"

Map syntax

environment:
  - NODE_ENV

Pass from host (no value)

environment:
  - NODE_ENV=${NODE_ENV:-development}

With default value

Environment

Environment Files

env_file: .env

Single env file

env_file:
  - .env
  - .env.local

Multiple env files

env_file:
  - path: .env
    required: false

Optional env file

💡 Variables in environment override env_file values

Environment

Variable Substitution

image: ${IMAGE_NAME}:${TAG}

Use shell variables

image: ${IMAGE:-nginx}:${TAG:-latest}

With defaults

ports:
  - "${HOST_PORT}:80"

Variable in ports

Dependencies

depends_on

depends_on:
  - db
  - redis

Simple dependency (start order)

depends_on:
  db:
    condition: service_started

Wait for service to start

depends_on:
  db:
    condition: service_healthy

Wait for healthcheck

depends_on:
  db:
    condition: service_completed_successfully

Wait for completion

💡 depends_on only controls start order, not readiness

Dependencies

Links (Legacy)

links:
  - db
  - cache:redis

Link to services

💡 Links are legacy. Use networks and depends_on instead

Dependencies

External Links

external_links:
  - redis_1
  - project_db_1:mysql

Link to external containers

Healthcheck

Healthcheck Configuration

healthcheck:
  test: ["CMD", "curl", "-f", "http://localhost"]
  interval: 30s
  timeout: 10s
  retries: 3

HTTP healthcheck

healthcheck:
  test: ["CMD-SHELL", "pg_isready -U postgres"]
  interval: 10s

Database healthcheck

healthcheck:
  test: ["CMD", "redis-cli", "ping"]

Redis healthcheck

healthcheck:
  disable: true

Disable healthcheck

Healthcheck

Healthcheck Options

interval: 30s

Time between checks

timeout: 10s

Timeout for single check

retries: 3

Consecutive failures to unhealthy

start_period: 40s

Grace period for startup

start_interval: 5s

Interval during start period

Advanced

Labels

labels:
  com.example.description: "Web app"

Add metadata labels

labels:
  - "com.example.env=production"

Array syntax

labels:
  traefik.enable: "true"
  traefik.http.routers.web.rule: "Host(`example.com`)"

Traefik labels

Advanced

Logging

logging:
  driver: json-file
  options:
    max-size: "10m"
    max-file: "3"

JSON file logging with rotation

logging:
  driver: syslog
  options:
    syslog-address: "tcp://192.168.0.42:123"

Syslog driver

logging:
  driver: none

Disable logging

Advanced

Resource Limits

deploy:
  resources:
    limits:
      cpus: '0.5'
      memory: 512M

CPU and memory limits

deploy:
  resources:
    reservations:
      cpus: '0.25'
      memory: 256M

Resource reservations

deploy:
  replicas: 3

Number of replicas

Advanced

DNS & Hosts

dns:
  - 8.8.8.8
  - 8.8.4.4

Custom DNS servers

dns_search:
  - example.com

DNS search domains

extra_hosts:
  - "host.docker.internal:host-gateway"

Add host entries

Advanced

Devices & Capabilities

devices:
  - "/dev/ttyUSB0:/dev/ttyUSB0"

Map devices

cap_add:
  - SYS_PTRACE

Add capabilities

cap_drop:
  - NET_ADMIN

Drop capabilities

Advanced

Extends & Profiles

extends:
  file: common.yml
  service: webapp

Extend another service

profiles:
  - debug

Assign to profile

💡 Use profiles to selectively start services: docker compose --profile debug up

Quick Reference

Start:

docker compose up -d

Stop:

docker compose down

Logs:

docker compose logs -f

Shell:

docker compose exec svc sh

Categories

  • CLI Commands

    Essential docker compose commands for managing containers.

  • Services

    Define containers, images, builds, ports, and commands.

  • Volumes

    Persist data and share files between host and containers.

  • Networks

    Configure networking between containers and external access.

  • Environment

    Set environment variables and use .env files.

  • Advanced

    Healthchecks, dependencies, labels, and more.

Basic Example

# docker-compose.yml
services:
  web:
    build: .
    ports:
      - "5000:5000"
    volumes:
      - .:/code
    depends_on:
      - redis
  redis:
    image: redis:alpine