TExcelTAD
Home › Docker Compose › Mini Project: Full-Stack App

Mini Project: Full-Stack App

Time to build a complete Compose setup from scratch: Taskboard, a small team task tracker. It has everything a real application has:

  • web: an nginx container serving the single-page frontend and proxying /api to the API,
  • api: a Python (Flask/Gunicorn) JSON API,
  • worker: a Celery worker that sends reminders and builds reports, using the API's image,
  • db: PostgreSQL for the data,
  • redis: the Celery broker and a cache.

You'll write one base file with what every environment shares, a development override for fast feedback, and a production override for the server, and verify each layer with docker compose config. The application code itself isn't the point here (the Docker project builds an API step by step); this project is about the Compose side.

text
                     host :8080 (dev) / :80 (prod)
                              │
                       ┌──────▼──────┐
     frontend network  │     web     │   nginx: SPA + /api proxy
                       └──────┬──────┘
                              │ api:5000
                       ┌──────▼──────┐
                       │     api     │   on frontend AND backend
                       └──┬───────┬──┘
     backend network      │       │            (internal: no internet)
       ┌──────────────────┘       └─────────────────┐
 ┌─────▼─────┐   ┌───────────┐   ┌──────────────┐   │
 │    db     │◀──│  worker   │──▶│    redis     │◀──┘
 │ postgres  │   │ (celery)  │   │ broker/cache │
 └───────────┘   └───────────┘   └──────────────┘

Step 1: plan the startup order

Before writing YAML, decide who waits for whom. db and redis have no dependencies; api and worker need both to be healthy (accepting connections, not just started); web needs a healthy api. A model of how Compose turns that into start waves, with the time each service takes to become healthy:

python · try it yourself
deps = {
    "db": [], "redis": [],
    "api": ["db", "redis"], "worker": ["db", "redis"],
    "web": ["api"],
}
healthy_after = {"db": 4, "redis": 1, "api": 6, "worker": 0, "web": 1}   # seconds after start

ready, started, t = {}, {}, 0
while len(ready) < len(deps):
    for svc, needs in deps.items():
        if svc not in started and all(d in ready and ready[d] <= t for d in needs):
            started[svc] = t
            ready[svc] = t + healthy_after[svc]
            print(f"t={t:>2}s start {svc:<7} (waited for: {', '.join(needs) or 'nothing'})")
    t = min(v for v in ready.values() if v > t) if any(v > t for v in ready.values()) else t + 1

print(f"\nall healthy at t={max(ready.values())}s")
print("start waves:", " -> ".join(
    "{" + ", ".join(sorted(s for s in started if started[s] == w)) + "}" for w in sorted(set(started.values()))))
t= 0s start db      (waited for: nothing)
t= 0s start redis   (waited for: nothing)
t= 4s start api     (waited for: db, redis)
t= 4s start worker  (waited for: db, redis)
t=10s start web     (waited for: api)

all healthy at t=11s
start waves: {db, redis} -> {api, worker} -> {web}

worker has no healthcheck of its own (Celery workers don't serve HTTP), so nothing waits for it. That's fine: no service depends on it.

Step 2: the base file

The base file is environment-neutral: no published debug ports, no source mounts, no production tags. The API and the worker share image, environment, secret and dependencies through an x-app fragment. The database password is a secret, and both images read it through the _FILE convention.

compose · try it yourself
# $ docker compose config --services
# $ docker compose config --images
# $ docker compose config --networks
# $ docker compose config --volumes
name: taskboard

x-app: &app
  image: ghcr.io/acme/taskboard-api:${API_TAG:-dev}
  build: ./api
  environment:
    DATABASE_URL: postgres://taskboard@db:5432/taskboard
    DB_PASSWORD_FILE: /run/secrets/db_password
    REDIS_URL: redis://redis:6379/0
  secrets: [db_password]
  depends_on:
    db: {condition: service_healthy}
    redis: {condition: service_healthy}

services:
  web:
    image: ghcr.io/acme/taskboard-web:${WEB_TAG:-dev}
    build: ./web
    ports: ["${WEB_PORT:-8080}:80"]
    depends_on:
      api: {condition: service_healthy}
    networks: [frontend]

  api:
    <<: *app
    command: ["gunicorn", "taskboard.wsgi", "--bind", "0.0.0.0:5000"]
    healthcheck:
      test: ["CMD", "python", "-c", "import urllib.request as u; u.urlopen('http://localhost:5000/health')"]
      interval: 10s
      start_period: 20s
    networks: [frontend, backend]

  worker:
    <<: *app
    command: ["celery", "-A", "taskboard", "worker", "--loglevel", "info"]
    networks: [backend]

  db:
    image: postgres:17
    environment:
      POSTGRES_USER: taskboard
      POSTGRES_PASSWORD_FILE: /run/secrets/db_password
    secrets: [db_password]
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U taskboard"]
      interval: 5s
      retries: 10
    volumes: [pgdata:/var/lib/postgresql/data]
    networks: [backend]

  redis:
    image: redis:8
    command: ["redis-server", "--appendonly", "yes"]
    healthcheck:
      test: ["CMD", "redis-cli", "ping"]
      interval: 5s
    volumes: [redisdata:/data]
    networks: [backend]

networks:
  frontend:
  backend:
    internal: true

volumes:
  pgdata:
  redisdata:

secrets:
  db_password:
    file: ./secrets/db_password.txt
# --- secrets/db_password.txt
dev-only-password
$ docker compose config --services
api
db
redis
web
worker
$ docker compose config --images
ghcr.io/acme/taskboard-api:dev
ghcr.io/acme/taskboard-api:dev
ghcr.io/acme/taskboard-web:dev
postgres:17
redis:8
$ docker compose config --networks
backend
frontend
$ docker compose config --volumes
pgdata
redisdata

The lists confirm the shape: five services, two networks, two volumes. --images shows the API image twice because api and worker both use it; Compose builds it once per service that has a build, and BuildKit's cache makes the second build instant.

Now look at the rendered worker, which comes almost entirely from the fragment. config worker prints the service and its dependencies:

compose · try it yourself
# $ docker compose config --no-path-resolution worker
name: taskboard

x-app: &app
  image: ghcr.io/acme/taskboard-api:${API_TAG:-dev}
  build: ./api
  environment:
    DATABASE_URL: postgres://taskboard@db:5432/taskboard
    DB_PASSWORD_FILE: /run/secrets/db_password
    REDIS_URL: redis://redis:6379/0
  secrets: [db_password]
  depends_on:
    db: {condition: service_healthy}
    redis: {condition: service_healthy}

services:
  web:
    image: ghcr.io/acme/taskboard-web:${WEB_TAG:-dev}
    build: ./web
    ports: ["${WEB_PORT:-8080}:80"]
    depends_on:
      api: {condition: service_healthy}
    networks: [frontend]

  api:
    <<: *app
    command: ["gunicorn", "taskboard.wsgi", "--bind", "0.0.0.0:5000"]
    healthcheck:
      test: ["CMD", "python", "-c", "import urllib.request as u; u.urlopen('http://localhost:5000/health')"]
      interval: 10s
      start_period: 20s
    networks: [frontend, backend]

  worker:
    <<: *app
    command: ["celery", "-A", "taskboard", "worker", "--loglevel", "info"]
    networks: [backend]

  db:
    image: postgres:17
    environment:
      POSTGRES_USER: taskboard
      POSTGRES_PASSWORD_FILE: /run/secrets/db_password
    secrets: [db_password]
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U taskboard"]
      interval: 5s
      retries: 10
    volumes: [pgdata:/var/lib/postgresql/data]
    networks: [backend]

  redis:
    image: redis:8
    command: ["redis-server", "--appendonly", "yes"]
    healthcheck:
      test: ["CMD", "redis-cli", "ping"]
      interval: 5s
    volumes: [redisdata:/data]
    networks: [backend]

networks:
  frontend:
  backend:
    internal: true

volumes:
  pgdata:
  redisdata:

secrets:
  db_password:
    file: ./secrets/db_password.txt
# --- secrets/db_password.txt
dev-only-password
name: taskboard
services:
  db:
    environment:
      POSTGRES_PASSWORD_FILE: /run/secrets/db_password
      POSTGRES_USER: taskboard
    image: postgres:17
    networks:
      backend: null
    secrets:
      - source: db_password
        target: /run/secrets/db_password
    volumes:
      - type: volume
        source: pgdata
        target: /var/lib/postgresql/data
        volume: {}
    healthcheck:
      test:
        - CMD-SHELL
        - pg_isready -U taskboard
      interval: 5s
      retries: 10
  redis:
    command:
      - redis-server
      - --appendonly
      - 'yes'
    image: redis:8
    networks:
      backend: null
    volumes:
      - type: volume
        source: redisdata
        target: /data
        volume: {}
    healthcheck:
      test:
        - CMD
        - redis-cli
        - ping
      interval: 5s
  worker:
    command:
      - celery
      - -A
      - taskboard
      - worker
      - --loglevel
      - info
    environment:
      DATABASE_URL: postgres://taskboard@db:5432/taskboard
      DB_PASSWORD_FILE: /run/secrets/db_password
      REDIS_URL: redis://redis:6379/0
    image: ghcr.io/acme/taskboard-api:dev
    networks:
      backend: null
    secrets:
      - source: db_password
        target: /run/secrets/db_password
    build:
      context: ./api
      dockerfile: Dockerfile
    depends_on:
      db:
        condition: service_healthy
        required: true
      redis:
        condition: service_healthy
        required: true
networks:
  backend:
    name: taskboard_backend
    internal: true
volumes:
  pgdata:
    name: taskboard_pgdata
  redisdata:
    name: taskboard_redisdata
secrets:
  db_password:
    name: taskboard_db_password
    file: ./secrets/db_password.txt
x-app:
  build: ./api
  depends_on:
    db:
      condition: service_healthy
    redis:
      condition: service_healthy
  environment:
    DATABASE_URL: postgres://taskboard@db:5432/taskboard
    DB_PASSWORD_FILE: /run/secrets/db_password
    REDIS_URL: redis://redis:6379/0
  image: ghcr.io/acme/taskboard-api:dev
  secrets:
    - db_password

Check the details against the plan: depends_on with service_healthy for both db and redis, the secret mounted at /run/secrets/db_password, everything on the internal backend network, and resources named taskboard_… because of the top-level name:. The x-app block is carried along at the end, ignored by Compose.

Note: the worker is only on the internal network, so it can't reach the internet. If it must send email through an external SMTP server, add it to a non-internal network too (or give it its own egress network).

Step 3: the development override

compose.override.yaml is loaded automatically by docker compose up. It switches the API to the Flask debug server built from a dev stage, publishes ports only on localhost, adds watch rules, and offers a database UI behind the tools profile:

compose · try it yourself
# $ docker compose config --services
# $ docker compose --profile tools config --services
# $ docker compose config --no-path-resolution api
name: taskboard

x-app: &app
  image: ghcr.io/acme/taskboard-api:${API_TAG:-dev}
  build: ./api
  environment:
    DATABASE_URL: postgres://taskboard@db:5432/taskboard
    DB_PASSWORD_FILE: /run/secrets/db_password
    REDIS_URL: redis://redis:6379/0
  secrets: [db_password]
  depends_on:
    db: {condition: service_healthy}
    redis: {condition: service_healthy}

services:
  web:
    image: ghcr.io/acme/taskboard-web:${WEB_TAG:-dev}
    build: ./web
    ports: ["${WEB_PORT:-8080}:80"]
    depends_on:
      api: {condition: service_healthy}
    networks: [frontend]

  api:
    <<: *app
    command: ["gunicorn", "taskboard.wsgi", "--bind", "0.0.0.0:5000"]
    healthcheck:
      test: ["CMD", "python", "-c", "import urllib.request as u; u.urlopen('http://localhost:5000/health')"]
      interval: 10s
      start_period: 20s
    networks: [frontend, backend]

  worker:
    <<: *app
    command: ["celery", "-A", "taskboard", "worker", "--loglevel", "info"]
    networks: [backend]

  db:
    image: postgres:17
    environment:
      POSTGRES_USER: taskboard
      POSTGRES_PASSWORD_FILE: /run/secrets/db_password
    secrets: [db_password]
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U taskboard"]
      interval: 5s
      retries: 10
    volumes: [pgdata:/var/lib/postgresql/data]
    networks: [backend]

  redis:
    image: redis:8
    command: ["redis-server", "--appendonly", "yes"]
    healthcheck:
      test: ["CMD", "redis-cli", "ping"]
      interval: 5s
    volumes: [redisdata:/data]
    networks: [backend]

networks:
  frontend:
  backend:
    internal: true

volumes:
  pgdata:
  redisdata:

secrets:
  db_password:
    file: ./secrets/db_password.txt

# --- compose.override.yaml
services:
  api:
    build:
      target: dev
    command: ["flask", "--app", "taskboard", "run", "--debug", "--host", "0.0.0.0", "--port", "5000"]
    ports: ["127.0.0.1:5000:5000"]
    environment:
      LOG_LEVEL: debug
    develop:
      watch:
        - {action: sync, path: ./api/taskboard, target: /app/taskboard}
        - {action: rebuild, path: ./api/requirements.txt}
  worker:
    develop:
      watch:
        - {action: sync+restart, path: ./api/taskboard, target: /app/taskboard}
  db:
    ports: ["127.0.0.1:5432:5432"]
  adminer:
    image: adminer:5
    profiles: [tools]
    ports: ["127.0.0.1:8081:8080"]
    networks: [backend]

# --- secrets/db_password.txt
dev-only-password
$ docker compose config --services
api
db
redis
web
worker
$ docker compose --profile tools config --services
adminer
api
db
redis
web
worker
$ docker compose config --no-path-resolution api
name: taskboard
services:
  api:
    develop:
      watch:
        - path: ./api/taskboard
          action: sync
          target: /app/taskboard
        - path: ./api/requirements.txt
          action: rebuild
    command:
      - flask
      - --app
      - taskboard
      - run
      - --debug
      - --host
      - 0.0.0.0
      - --port
      - "5000"
    environment:
      DATABASE_URL: postgres://taskboard@db:5432/taskboard
      DB_PASSWORD_FILE: /run/secrets/db_password
      LOG_LEVEL: debug
      REDIS_URL: redis://redis:6379/0
    image: ghcr.io/acme/taskboard-api:dev
    networks:
      backend: null
      frontend: null
    secrets:
      - source: db_password
        target: /run/secrets/db_password
    build:
      context: ./api
      dockerfile: Dockerfile
      target: dev
    depends_on:
      db:
        condition: service_healthy
        required: true
      redis:
        condition: service_healthy
        required: true
    healthcheck:
      test:
        - CMD
        - python
        - -c
        - import urllib.request as u; u.urlopen('http://localhost:5000/health')
      interval: 10s
      start_period: 20s
    ports:
      - mode: ingress
        host_ip: 127.0.0.1
        target: 5000
        published: "5000"
        protocol: tcp
  db:
    environment:
      POSTGRES_PASSWORD_FILE: /run/secrets/db_password
      POSTGRES_USER: taskboard
    image: postgres:17
    networks:
      backend: null
    secrets:
      - source: db_password
        target: /run/secrets/db_password
    volumes:
      - type: volume
        source: pgdata
        target: /var/lib/postgresql/data
        volume: {}
    healthcheck:
      test:
        - CMD-SHELL
        - pg_isready -U taskboard
      interval: 5s
      retries: 10
    ports:
      - mode: ingress
        host_ip: 127.0.0.1
        target: 5432
        published: "5432"
        protocol: tcp
  redis:
    command:
      - redis-server
      - --appendonly
      - 'yes'
    image: redis:8
    networks:
      backend: null
    volumes:
      - type: volume
        source: redisdata
        target: /data
        volume: {}
    healthcheck:
      test:
        - CMD
        - redis-cli
        - ping
      interval: 5s
networks:
  backend:
    name: taskboard_backend
    internal: true
  frontend:
    name: taskboard_frontend
volumes:
  pgdata:
    name: taskboard_pgdata
  redisdata:
    name: taskboard_redisdata
secrets:
  db_password:
    name: taskboard_db_password
    file: ./secrets/db_password.txt
x-app:
  build: ./api
  depends_on:
    db:
      condition: service_healthy
    redis:
      condition: service_healthy
  environment:
    DATABASE_URL: postgres://taskboard@db:5432/taskboard
    DB_PASSWORD_FILE: /run/secrets/db_password
    REDIS_URL: redis://redis:6379/0
  image: ghcr.io/acme/taskboard-api:dev
  secrets:
    - db_password

Read the merged api carefully, because it shows every merge rule from Override Files & Merging at once:

  • build: ./api (a string) and build: {target: dev} merged into one mapping with context, dockerfile and target;
  • command replaced by the Flask one;
  • environment merged by key: the three shared variables plus LOG_LEVEL: debug;
  • ports added, bound to 127.0.0.1;
  • develop.watch added; the healthcheck, secret and networks kept from the base.

The day-to-day commands for this setup:

bash
$ cp .env.example .env && echo "dev-only-password" > secrets/db_password.txt   # once
$ docker compose up --watch                       # everything, with file sync
$ docker compose --profile tools up -d adminer    # database UI on http://localhost:8081
$ docker compose run --rm api pytest -q           # tests against the real db and redis
$ docker compose exec db psql -U taskboard        # SQL console
$ docker compose down                             # stop (data stays in the volumes)

Step 4: the production override

On the server, the images come from the registry with explicit tags, nothing is built, only web is published, and every service gets a restart policy, rotated logs and limits. Three worker replicas handle the background jobs:

compose · try it yourself
# $ docker compose -f compose.yaml -f compose.prod.yaml config --images
# $ docker compose -f compose.yaml -f compose.prod.yaml config worker
name: taskboard

x-app: &app
  image: ghcr.io/acme/taskboard-api:${API_TAG:-dev}
  build: ./api
  environment:
    DATABASE_URL: postgres://taskboard@db:5432/taskboard
    DB_PASSWORD_FILE: /run/secrets/db_password
    REDIS_URL: redis://redis:6379/0
  secrets: [db_password]
  depends_on:
    db: {condition: service_healthy}
    redis: {condition: service_healthy}

services:
  web:
    image: ghcr.io/acme/taskboard-web:${WEB_TAG:-dev}
    build: ./web
    ports: ["${WEB_PORT:-8080}:80"]
    depends_on:
      api: {condition: service_healthy}
    networks: [frontend]

  api:
    <<: *app
    command: ["gunicorn", "taskboard.wsgi", "--bind", "0.0.0.0:5000"]
    healthcheck:
      test: ["CMD", "python", "-c", "import urllib.request as u; u.urlopen('http://localhost:5000/health')"]
      interval: 10s
      start_period: 20s
    networks: [frontend, backend]

  worker:
    <<: *app
    command: ["celery", "-A", "taskboard", "worker", "--loglevel", "info"]
    networks: [backend]

  db:
    image: postgres:17
    environment:
      POSTGRES_USER: taskboard
      POSTGRES_PASSWORD_FILE: /run/secrets/db_password
    secrets: [db_password]
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U taskboard"]
      interval: 5s
      retries: 10
    volumes: [pgdata:/var/lib/postgresql/data]
    networks: [backend]

  redis:
    image: redis:8
    command: ["redis-server", "--appendonly", "yes"]
    healthcheck:
      test: ["CMD", "redis-cli", "ping"]
      interval: 5s
    volumes: [redisdata:/data]
    networks: [backend]

networks:
  frontend:
  backend:
    internal: true

volumes:
  pgdata:
  redisdata:

secrets:
  db_password:
    file: ./secrets/db_password.txt

# --- compose.prod.yaml
x-prod: &prod
  restart: unless-stopped
  logging:
    driver: local
    options: {max-size: 20m, max-file: "5"}

services:
  web:
    <<: *prod
    build: !reset null
    image: ghcr.io/acme/taskboard-web:${WEB_TAG:?set WEB_TAG}
    ports: !override ["80:80"]
  api:
    <<: *prod
    build: !reset null
    image: ghcr.io/acme/taskboard-api:${API_TAG:?set API_TAG}
    deploy:
      resources:
        limits: {cpus: "1.0", memory: 512M}
  worker:
    <<: *prod
    build: !reset null
    image: ghcr.io/acme/taskboard-api:${API_TAG:?set API_TAG}
    deploy:
      replicas: 3
      resources:
        limits: {cpus: "0.5", memory: 384M}
  db:
    <<: *prod
    image: postgres:17.6
    deploy:
      resources:
        limits: {memory: 1G}
  redis:
    <<: *prod
    image: redis:8.2

# --- .env
API_TAG=1.4.0
WEB_TAG=1.4.0

# --- secrets/db_password.txt
not-the-real-password
$ docker compose -f compose.yaml -f compose.prod.yaml config --images
ghcr.io/acme/taskboard-api:1.4.0
ghcr.io/acme/taskboard-api:1.4.0
ghcr.io/acme/taskboard-web:1.4.0
postgres:17.6
redis:8.2
$ docker compose -f compose.yaml -f compose.prod.yaml config worker
name: taskboard
services:
  db:
    deploy:
      resources:
        limits:
          memory: "1073741824"
    restart: unless-stopped
    environment:
      POSTGRES_PASSWORD_FILE: /run/secrets/db_password
      POSTGRES_USER: taskboard
    image: postgres:17.6
    logging:
      driver: local
      options:
        max-file: "5"
        max-size: 20m
    networks:
      backend: null
    secrets:
      - source: db_password
        target: /run/secrets/db_password
    volumes:
      - type: volume
        source: pgdata
        target: /var/lib/postgresql/data
        volume: {}
    healthcheck:
      test:
        - CMD-SHELL
        - pg_isready -U taskboard
      interval: 5s
      retries: 10
  redis:
    restart: unless-stopped
    command:
      - redis-server
      - --appendonly
      - 'yes'
    image: redis:8.2
    logging:
      driver: local
      options:
        max-file: "5"
        max-size: 20m
    networks:
      backend: null
    volumes:
      - type: volume
        source: redisdata
        target: /data
        volume: {}
    healthcheck:
      test:
        - CMD
        - redis-cli
        - ping
      interval: 5s
  worker:
    deploy:
      replicas: 3
      resources:
        limits:
          cpus: 0.5
          memory: "402653184"
    restart: unless-stopped
    command:
      - celery
      - -A
      - taskboard
      - worker
      - --loglevel
      - info
    environment:
      DATABASE_URL: postgres://taskboard@db:5432/taskboard
      DB_PASSWORD_FILE: /run/secrets/db_password
      REDIS_URL: redis://redis:6379/0
    image: ghcr.io/acme/taskboard-api:1.4.0
    logging:
      driver: local
      options:
        max-file: "5"
        max-size: 20m
    networks:
      backend: null
    secrets:
      - source: db_password
        target: /run/secrets/db_password
    depends_on:
      db:
        condition: service_healthy
        required: true
      redis:
        condition: service_healthy
        required: true
networks:
  backend:
    name: taskboard_backend
    internal: true
volumes:
  pgdata:
    name: taskboard_pgdata
  redisdata:
    name: taskboard_redisdata
secrets:
  db_password:
    name: taskboard_db_password
    file: /home/ada/demo/secrets/db_password.txt
x-app:
  build: ./api
  depends_on:
    db:
      condition: service_healthy
    redis:
      condition: service_healthy
  environment:
    DATABASE_URL: postgres://taskboard@db:5432/taskboard
    DB_PASSWORD_FILE: /run/secrets/db_password
    REDIS_URL: redis://redis:6379/0
  image: ghcr.io/acme/taskboard-api:1.4.0
  secrets:
    - db_password
x-prod:
  logging:
    driver: local
    options:
      max-file: "5"
      max-size: 20m
  restart: unless-stopped

What to verify in this output:

  • every image has a pinned tag (1.4.0, postgres:17.6, redis:8.2), and there's no build left;
  • the worker has replicas: 3 and a memory limit of 384 MiB (printed in bytes);
  • restart: unless-stopped and local logging with rotation on every service, coming from the x-prod fragment of the production file (anchors can't cross files, so the production file defines its own);
  • there's no override file in the list: with -f, compose.override.yaml is not loaded, so no debug ports or watch rules leak into production.

And the safety net: forgetting a tag stops the deploy before anything happens.

compose · try it yourself
# $ docker compose -f compose.yaml -f compose.prod.yaml config -q
name: taskboard

x-app: &app
  image: ghcr.io/acme/taskboard-api:${API_TAG:-dev}
  build: ./api
  environment:
    DATABASE_URL: postgres://taskboard@db:5432/taskboard
    DB_PASSWORD_FILE: /run/secrets/db_password
    REDIS_URL: redis://redis:6379/0
  secrets: [db_password]
  depends_on:
    db: {condition: service_healthy}
    redis: {condition: service_healthy}

services:
  web:
    image: ghcr.io/acme/taskboard-web:${WEB_TAG:-dev}
    build: ./web
    ports: ["${WEB_PORT:-8080}:80"]
    depends_on:
      api: {condition: service_healthy}
    networks: [frontend]

  api:
    <<: *app
    command: ["gunicorn", "taskboard.wsgi", "--bind", "0.0.0.0:5000"]
    healthcheck:
      test: ["CMD", "python", "-c", "import urllib.request as u; u.urlopen('http://localhost:5000/health')"]
      interval: 10s
      start_period: 20s
    networks: [frontend, backend]

  worker:
    <<: *app
    command: ["celery", "-A", "taskboard", "worker", "--loglevel", "info"]
    networks: [backend]

  db:
    image: postgres:17
    environment:
      POSTGRES_USER: taskboard
      POSTGRES_PASSWORD_FILE: /run/secrets/db_password
    secrets: [db_password]
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U taskboard"]
      interval: 5s
      retries: 10
    volumes: [pgdata:/var/lib/postgresql/data]
    networks: [backend]

  redis:
    image: redis:8
    command: ["redis-server", "--appendonly", "yes"]
    healthcheck:
      test: ["CMD", "redis-cli", "ping"]
      interval: 5s
    volumes: [redisdata:/data]
    networks: [backend]

networks:
  frontend:
  backend:
    internal: true

volumes:
  pgdata:
  redisdata:

secrets:
  db_password:
    file: ./secrets/db_password.txt

# --- compose.prod.yaml
x-prod: &prod
  restart: unless-stopped
  logging:
    driver: local
    options: {max-size: 20m, max-file: "5"}

services:
  web:
    <<: *prod
    build: !reset null
    image: ghcr.io/acme/taskboard-web:${WEB_TAG:?set WEB_TAG}
    ports: !override ["80:80"]
  api:
    <<: *prod
    build: !reset null
    image: ghcr.io/acme/taskboard-api:${API_TAG:?set API_TAG}
    deploy:
      resources:
        limits: {cpus: "1.0", memory: 512M}
  worker:
    <<: *prod
    build: !reset null
    image: ghcr.io/acme/taskboard-api:${API_TAG:?set API_TAG}
    deploy:
      replicas: 3
      resources:
        limits: {cpus: "0.5", memory: 384M}
  db:
    <<: *prod
    image: postgres:17.6
    deploy:
      resources:
        limits: {memory: 1G}
  redis:
    <<: *prod
    image: redis:8.2

# --- .env
WEB_TAG=1.4.0

# --- secrets/db_password.txt
not-the-real-password
error while interpolating services.api.image: required variable API_TAG is missing a value: set API_TAG
error while interpolating services.worker.image: required variable API_TAG is missing a value: set API_TAG

Step 5: a release check

Before each deploy, CI renders the production config and checks a few rules (see Compose in CI). A sketch of such a check, run on a summary of the rendered production services:

python · try it yourself
prod = {
    "web":    {"image": "ghcr.io/acme/taskboard-web:1.4.0", "ports": ["80:80"], "restart": "unless-stopped", "memory": None},
    "api":    {"image": "ghcr.io/acme/taskboard-api:1.4.0", "ports": [], "restart": "unless-stopped", "memory": "512M"},
    "worker": {"image": "ghcr.io/acme/taskboard-api:1.4.0", "ports": [], "restart": "unless-stopped", "memory": "384M"},
    "db":     {"image": "postgres:17.6", "ports": [], "restart": "unless-stopped", "memory": "1G"},
    "redis":  {"image": "redis:8.2", "ports": [], "restart": "unless-stopped", "memory": None},
}

def check(name, svc):
    problems = []
    tag = svc["image"].rsplit(":", 1)[-1]
    if tag in ("latest", "dev") or "." not in tag:
        problems.append(f"image tag '{tag}' is not a pinned version")
    if svc["ports"] and name != "web":
        problems.append("publishes ports, only web may")
    if svc["restart"] not in ("always", "unless-stopped"):
        problems.append("no restart policy")
    if svc["memory"] is None:
        problems.append("no memory limit")
    return problems

failed = False
for name, svc in prod.items():
    problems = check(name, svc)
    failed |= bool(problems)
    print(f"{'FAIL' if problems else 'ok  '} {name:<7} {'; '.join(problems)}")
print("\nrelease", "blocked" if failed else "approved")
FAIL web     no memory limit
ok   api
ok   worker
ok   db
FAIL redis   no memory limit

release blocked

The check catches two real gaps: web and redis have no memory limit. Add deploy.resources.limits.memory for them in compose.prod.yaml (for example 128M and 256M), and the release is approved.

Step 6: deploy

On the server (sample session):

bash
$ export API_TAG=1.4.0 WEB_TAG=1.4.0
$ docker compose -f compose.yaml -f compose.prod.yaml pull
$ docker compose -f compose.yaml -f compose.prod.yaml up -d --no-build --wait
[+] Running 9/9
 ✔ Network taskboard_frontend    Created
 ✔ Network taskboard_backend     Created
 ✔ Volume "taskboard_pgdata"     Created
 ✔ Volume "taskboard_redisdata"  Created
 ✔ Container taskboard-db-1      Healthy
 ✔ Container taskboard-redis-1   Healthy
 ✔ Container taskboard-api-1     Healthy
 ✔ Container taskboard-worker-1  Started
 ✔ Container taskboard-worker-2  Started
 ✔ Container taskboard-worker-3  Started
 ✔ Container taskboard-web-1     Started
$ docker compose -f compose.yaml -f compose.prod.yaml ps --format 'table {{.Name}}\t{{.Status}}'
NAME                 STATUS
taskboard-api-1      Up 41 seconds (healthy)
taskboard-db-1       Up 52 seconds (healthy)
taskboard-redis-1    Up 52 seconds (healthy)
taskboard-web-1      Up 30 seconds
taskboard-worker-1   Up 41 seconds
taskboard-worker-2   Up 41 seconds
taskboard-worker-3   Up 41 seconds

Ideas for going further

  1. Add the missing memory limits from Step 5 and a healthcheck for web (wget -qO- http://localhost/).
  2. Add a backup service in a tools profile that runs pg_dump into a bind-mounted ./backups folder.
  3. Put Caddy in front of web for automatic HTTPS (see Compose in Production).
  4. Write compose.ci.yaml: tmpfs database, a tests service, and run it with docker compose run --rm tests.
  5. Render the production file and deploy it as a Swarm stack (From Compose to Swarm): what do you have to remove?
  6. Convert it for Kubernetes (From Compose to Kubernetes) and compare the result with the Kubernetes project.

Test yourself

Why is compose.override.yaml not applied in the production command?

  1. Production ignores overrides by default
  2. Because the command names its files with -f, which disables the automatic override
  3. Because COMPOSE_PROFILES is empty
  4. Because of !reset

How do api and worker share their image, environment, secret and dependencies in the base file?

  1. extends
  2. include
  3. An x-app fragment merged with <<: *app
  4. A profile

What makes the production deploy fail early when API_TAG is missing?

  1. A healthcheck
  2. The ${API_TAG:?set API_TAG} interpolation in compose.prod.yaml
  3. pull_policy
  4. The registry