Docker

Docker Compose: Multi-Container Applications

Beginner
16 minutes
Updated October 2026

Define and run multi-container Docker applications with one YAML file — from basic setup to production patterns with volumes, networks, and health checks. This is the reference guide: every field that matters, with the context that makes it make sense.

Table of Contents

Compose File Basics

# docker-compose.yml
services:
  web:
    image: nginx:alpine
    ports:
      - "80:80"
  db:
    image: postgres:16
    environment:
      POSTGRES_PASSWORD: example
docker compose up -d
docker compose down
docker compose logs -f

Everything in Compose hangs off services: — each key is a container definition with its own image, ports, volumes, and config. One up builds the whole stack; one down tears it down cleanly.

The version field is deprecated in modern Compose — omit it. docker compose (space, the v2 plugin) is the current syntax; docker-compose (hyphen, the old Python tool) is legacy.

Services

Full Service Definition

services:
  api:
    build:
      context: ./api
      dockerfile: Dockerfile
    image: my-api:latest
    container_name: my-api
    restart: unless-stopped
    ports:
      - "3000:3000"
    environment:
      NODE_ENV: production
      DATABASE_URL: postgres://db:5432/myapp
    depends_on:
      db:
        condition: service_healthy
    volumes:
      - ./api:/app          # dev hot-reload
      - api-logs:/logs      # named volume
    networks:
      - backend
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:3000/health"]
      interval: 30s
      timeout: 5s
      retries: 3

The fields that carry the weight: restart decides what happens on crash/reboot, depends_on controls startup order, healthcheck is what makes depends_on meaningful (see below). container_name is usually not worth setting — it prevents scaling the service past one replica.

Build vs Image

# Option 1: Pre-built image — the production pattern
services:
  app:
    image: myregistry.com/app:1.2.0

# Option 2: Build from Dockerfile — the dev pattern
services:
  app:
    build: .
    image: my-app:dev

You can use both: build defines how to create the image, image names the result. docker compose build bakes it; up --build rebuilds only when the source changed.

Volumes and Persistence

Containers are disposable; volumes are where data survives. Two kinds you'll actually use:

Named Volumes

services:
  db:
    image: postgres:16
    volumes:
      - pgdata:/var/lib/postgresql/data

volumes:
  pgdata:    # Docker manages location

Named volumes persist across down/up — this is where databases live. Docker manages the storage; you manage the name.

Bind Mounts

services:
  app:
    volumes:
      - ./src:/app/src            # relative to compose file — code changes reflect instantly
      - /opt/app/logs:/var/log    # absolute host path

Bind mounts map a host path into the container — the dev pattern for hot reload (edit code on the host, the container sees it immediately). Avoid them for production data: host-path dependencies make the stack non-portable.

Read-Only Mounts

volumes:
  - ./nginx.conf:/etc/nginx/nginx.conf:ro

:ro mounts config that the container must never modify — a compromised nginx can't rewrite its own config file.

Networking

Default Network

All services in a compose file share a default network — and crucially, Docker's embedded DNS resolves service names:

services:
  web:
    image: myapp
    environment:
      DB_HOST: db    # ← service name resolves to IP
  db:
    image: postgres:16

db resolves to the database container's current IP — no hardcoded addresses, no links. This is Compose's killer feature: service discovery with zero config. Nothing is reachable from outside the network unless you publish a ports: mapping.

Custom Networks

services:
  frontend:
    networks:
      - frontend-net
  api:
    networks:
      - frontend-net
      - backend-net     # API bridges both
  db:
    networks:
      - backend-net     # isolated from frontend

networks:
  frontend-net:
  backend-net:

Multiple networks let you build real topology: db on backend-net only can never be reached by frontend, no matter what ports anyone publishes — segmentation enforced by the network, not by discipline.

Aliases

services:
  api:
    networks:
      backend:
        aliases:
          - api.internal

Aliases give a service extra DNS names — useful for matching a hostname your app already expects.

Environment Variables

Inline

environment:
  - NODE_ENV=production
  - LOG_LEVEL=info

.env File

# .env
DATABASE_URL=postgres://db:5432/myapp
API_KEY=abc123
services:
  app:
    env_file:
      - .env

Two different .env roles that confuse everyone: Compose reads .env itself for ${VAR} substitution in the YAML, and env_file: injects variables into the container. They're separate mechanisms — a .env value used for substitution doesn't reach the container unless you also pass it through environment: or env_file:.

Compose Variable Substitution

services:
  app:
    image: myapp:${TAG:-latest}
TAG=v1.2.0 docker compose up

${TAG:-latest} is the pattern for parameterized files — the same compose.yaml serves every environment, with the tag supplied at deploy time.

Health Checks and Dependencies

services:
  db:
    image: postgres:16
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U postgres"]
      interval: 5s
      timeout: 3s
      retries: 5

  api:
    depends_on:
      db:
        condition: service_healthy    # wait for healthy, not just started
      redis:
        condition: service_started    # just wait for start

Conditions: service_started (default — container launched, readiness unknown), service_healthy (healthcheck passing), service_completed_successfully (for init/migration containers that run once and exit). service_healthy is the one that matters — without it, depends_on only means "started first," and your app crashes connecting to a database that's still initializing.

Production Patterns

Restart Policies

services:
  app:
    restart: unless-stopped    # restart unless manually stopped
    # Other options: no, always, on-failure

unless-stopped is the right default for services: they come back after crashes and host reboots, but stay down when you deliberately stop them.

Resource Limits

services:
  app:
    deploy:
      resources:
        limits:
          cpus: '1.0'
          memory: 512M
        reservations:
          cpus: '0.25'
          memory: 128M

Limits prevent one greedy container from starving the host. On a single-host production box, memory limits are the difference between "one service leaks" and "everything OOMs."

Multi-Environment Override

# docker-compose.yml        — base
# docker-compose.prod.yml   — prod overrides

docker compose -f docker-compose.yml -f docker-compose.prod.yml up -d
# docker-compose.prod.yml
services:
  app:
    restart: always
    environment:
      LOG_LEVEL: warn

Later files win on conflicts — keep the base file dev-shaped and layer production hardening in the override. docker compose config shows the merged result; always check it before assuming your override applied.

Logging

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

Without this, a chatty container's stdout grows unboundedly until the disk fills — the most common self-inflicted Compose outage there is.

Common Commands

# Start all services (detached)
docker compose up -d

# View logs (follow)
docker compose logs -f api

# Scale a service
docker compose up -d --scale worker=3

# Rebuild and restart one service
docker compose up -d --build api

# Stop everything
docker compose down

# Stop + remove volumes (destroys data)
docker compose down -v

# See running services
docker compose ps

# Execute command in running container
docker compose exec db psql -U postgres

# View resolved config (after env substitution + file merging)
docker compose config

config is the underrated one — it renders the final YAML after env substitution and override merging, so "is my variable actually set?" is checkable instead of guessable.

Common Mistakes

1. Port Conflicts

# Both map to host port 80 — second one fails
services:
  web1: { ports: ["80:80"] }
  web2: { ports: ["80:80"] }   # ← conflict

# Fix: use different host ports
  web2: { ports: ["8080:80"] }

Container-internal ports can collide freely; published host ports can't. Only publish what needs to be reachable off the Docker network — db almost never needs a ports: mapping since other services reach it by name.

2. Secrets in Environment

# Bad — visible in docker inspect, logs, and ps
environment:
  DB_PASSWORD: supersecret

# Better — use secrets or .env
env_file:
  - .env    # add .env to .gitignore

Environment variables leak into docker inspect, process listings, and crash dumps. env_file keeps them out of the compose file; Compose secrets: mounts them as files for better isolation still.

3. Depending on Service Started vs Healthy

# Bad — api starts before db is ready
depends_on:
  - db

# Good — waits for health check
depends_on:
  db:
    condition: service_healthy

The single most common "works sometimes" Compose bug: depends_on without a healthcheck means "the container launched," not "Postgres accepts connections."

Written & Reviewed by Yasir Masood, CloudOpsGuide Editor

Our tutorials and troubleshooting runbooks are written by a DevOps practitioner with hands-on experience operating Kubernetes, Terraform, CI/CD pipelines, and Linux infrastructure in production. Commands, manifests, and configurations are verified against current tooling releases. Learn more about our editorial process or report a correction or outdated flag.