TExcelTAD
Home › Docker Swarm › Mini Project: A Highly Available Stack

Mini Project: A Highly Available Stack

In this project you design, write and stress-test the stack for a small shop: an nginx front proxy, a Python api, a PostgreSQL database and a visualizer dashboard that shows which task runs on which node. You will use most of the course: overlay networks with tiers, configs and secrets with versioned names, placement constraints and zone spreading, healthchecks, update and rollback policies, a production override file, and a model of what happens when nodes and a whole zone fail.

Every stack file step is checked with the real docker stack config, so you see exactly what docker stack deploy would receive. The failure drills run as Python models. At the end you get the deploy commands to try on a real swarm (three VMs are enough; see Creating a Swarm).

The finished project folder:

text
shop-stack/
├── stack.yaml          # the shared definition
├── prod.yaml           # production overrides (replicas, limits, ports)
├── nginx.conf          # proxy config, delivered as a Swarm config
└── deploy.sh           # exports variables, validates, deploys

Step 1: The cluster

Target layout: three availability zones, one manager per zone, and two workers per zone. manager-b and manager-c are drained (they run no tasks at all); manager-a stays active so that it can host the visualizer, and every application service is constrained to workers, so nothing else lands there. One worker in zone a has a fast SSD and the label db=true.

text
          zone a                    zone b                    zone c
 manager-a  (active)       manager-b  (drain)        manager-c  (drain)
 worker-a1  db=true        worker-b1                 worker-c1
 worker-a2                 worker-b2                 worker-c2
bash
$ for n in worker-a1 worker-a2; do docker node update --label-add zone=a $n; done
$ for n in worker-b1 worker-b2; do docker node update --label-add zone=b $n; done
$ for n in worker-c1 worker-c2; do docker node update --label-add zone=c $n; done
$ docker node update --label-add db=true worker-a1
$ for m in manager-b manager-c; do docker node update --availability drain $m; done

Before writing any YAML, check that this layout survives the failures we care about. Three managers, one per zone, keep quorum (2 of 3) when any one zone is lost (High Availability):

python · try it yourself
managers = {"manager-a": "a", "manager-b": "b", "manager-c": "c"}
quorum = len(managers) // 2 + 1
for lost_zone in "abc":
    alive = [m for m, z in managers.items() if z != lost_zone]
    print(f"zone {lost_zone} down: {len(alive)}/{len(managers)} managers, quorum {quorum} ->",
          "OK" if len(alive) >= quorum else "FROZEN")
zone a down: 2/3 managers, quorum 2 -> OK
zone b down: 2/3 managers, quorum 2 -> OK
zone c down: 2/3 managers, quorum 2 -> OK

Step 2: Services and networks

Start with the four services and two overlay networks. front connects the proxy to the api; back connects the api to the database and is internal (no route outside) and encrypted. The visualizer joins neither: it only needs the Docker socket on a manager.

compose · try it yourself
# $ docker stack config -c stack.yaml
# --- stack.yaml
services:
  proxy:
    image: nginx:1.27-alpine
    ports: ["80:8080"]
    networks: [front]
  api:
    image: ghcr.io/acme/shop-api:2.4.1
    networks: [front, back]
  db:
    image: postgres:17
    networks: [back]
  visualizer:
    image: dockersamples/visualizer:latest
    ports: ["8081:8080"]
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock:ro
networks:
  front:
    driver: overlay
  back:
    driver: overlay
    internal: true
    driver_opts:
      encrypted: "true"
version: "3.13"
services:
  api:
    image: ghcr.io/acme/shop-api:2.4.1
    networks:
      back: null
      front: null
  db:
    image: postgres:17
    networks:
      back: null
  proxy:
    image: nginx:1.27-alpine
    networks:
      front: null
    ports:
      - mode: ingress
        target: 8080
        published: 80
        protocol: tcp
  visualizer:
    image: dockersamples/visualizer:latest
    ports:
      - mode: ingress
        target: 8080
        published: 8081
        protocol: tcp
    volumes:
      - type: bind
        source: /var/run/docker.sock
        target: /var/run/docker.sock
        read_only: true
networks:
  back:
    driver: overlay
    driver_opts:
      encrypted: "true"
    internal: true
  front:
    driver: overlay

The proxy can reach api by name, the api can reach db, and the proxy can't resolve db at all (Service Discovery).

Step 3: Configs and secrets

The proxy config goes in a config with a versioned name, the database password in an external secret created before the first deploy:

bash
$ printf '%s' "$(openssl rand -base64 24)" | docker secret create shop_db_password_v1 -

The api and the database both read the password through the _FILE convention, and both mount it at the same stable path /run/secrets/db_password, whatever the version:

compose · try it yourself
# $ docker stack config -c stack.yaml
# --- stack.yaml
services:
  proxy:
    image: nginx:1.27-alpine
    configs:
      - source: nginx_conf
        target: /etc/nginx/conf.d/default.conf
  api:
    image: ghcr.io/acme/shop-api:2.4.1
    environment:
      DB_HOST: db
      DB_USER: shop
      DB_PASSWORD_FILE: /run/secrets/db_password
    secrets:
      - source: db_password
        target: db_password
  db:
    image: postgres:17
    environment:
      POSTGRES_USER: shop
      POSTGRES_PASSWORD_FILE: /run/secrets/db_password
    secrets:
      - source: db_password
        target: db_password
configs:
  nginx_conf:
    name: shop_nginx_${NGINX_CONF_REV:-1}
    file: ./nginx.conf
secrets:
  db_password:
    name: shop_db_password_${DB_PASSWORD_REV:-v1}
    external: true
# --- nginx.conf
server {
    listen 8080;
    location /healthz { return 200 "ok\n"; }
    location / { proxy_pass http://api:9000; }
}
version: "3.13"
services:
  api:
    environment:
      DB_HOST: db
      DB_PASSWORD_FILE: /run/secrets/db_password
      DB_USER: shop
    image: ghcr.io/acme/shop-api:2.4.1
    secrets:
      - source: db_password
        target: db_password
  db:
    environment:
      POSTGRES_PASSWORD_FILE: /run/secrets/db_password
      POSTGRES_USER: shop
    image: postgres:17
    secrets:
      - source: db_password
        target: db_password
  proxy:
    configs:
      - source: nginx_conf
        target: /etc/nginx/conf.d/default.conf
    image: nginx:1.27-alpine
secrets:
  db_password:
    name: shop_db_password_v1
    external: true
configs:
  nginx_conf:
    name: shop_nginx_1
    file: /home/ada/demo/nginx.conf

Changing nginx.conf now means bumping NGINX_CONF_REV; rotating the password means creating shop_db_password_v2 and deploying with DB_PASSWORD_REV=v2 (Secrets, with the database-side steps from that lesson).

Step 4: The complete stack file

Now add the orchestration policies. Read the comments: each line is a decision from the course.

compose · try it yourself
# $ docker stack config -c stack.yaml
# --- stack.yaml
x-update: &rolling
  parallelism: 1
  delay: 10s
  order: start-first          # new task healthy before the old one stops
  failure_action: rollback
  monitor: 30s

services:
  proxy:
    image: nginx:1.27-alpine
    ports: ["80:8080"]
    networks: [front]
    configs:
      - source: nginx_conf
        target: /etc/nginx/conf.d/default.conf
    healthcheck:
      test: ["CMD", "wget", "-qO-", "http://127.0.0.1:8080/healthz"]
      interval: 10s
      retries: 3
    deploy:
      replicas: 3
      placement:
        constraints: [node.role == worker]
        preferences: [spread: node.labels.zone]
      update_config: *rolling

  api:
    image: ghcr.io/acme/shop-api:${API_TAG:-2.4.1}
    networks: [front, back]
    environment:
      DB_HOST: db
      DB_USER: shop
      DB_PASSWORD_FILE: /run/secrets/db_password
    secrets:
      - source: db_password
        target: db_password
    healthcheck:
      test: ["CMD", "wget", "-qO-", "http://127.0.0.1:9000/health"]
      interval: 10s
      retries: 3
      start_period: 20s
    deploy:
      replicas: 3
      placement:
        constraints: [node.role == worker]
        preferences: [spread: node.labels.zone]
        max_replicas_per_node: 2
      resources:
        reservations: {cpus: "0.25", memory: 256M}
        limits: {memory: 512M}
      restart_policy: {condition: any, delay: 5s}
      update_config: *rolling
      rollback_config: {parallelism: 0, order: stop-first}

  db:
    image: postgres:17
    networks: [back]
    environment:
      POSTGRES_USER: shop
      POSTGRES_PASSWORD_FILE: /run/secrets/db_password
    secrets:
      - source: db_password
        target: db_password
    volumes:
      - pgdata:/var/lib/postgresql/data
    deploy:
      replicas: 1
      placement:
        constraints: [node.labels.db == true]   # the data lives on worker-a1
      resources:
        reservations: {memory: 1G}
      update_config:
        order: stop-first      # never two postgres processes on one data directory

  visualizer:
    image: dockersamples/visualizer:latest
    ports: ["8081:8080"]
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock:ro
    deploy:
      placement:
        constraints: [node.role == manager]

networks:
  front:
    driver: overlay
  back:
    driver: overlay
    internal: true
    driver_opts:
      encrypted: "true"
volumes:
  pgdata:
configs:
  nginx_conf:
    name: shop_nginx_${NGINX_CONF_REV:-1}
    file: ./nginx.conf
secrets:
  db_password:
    name: shop_db_password_${DB_PASSWORD_REV:-v1}
    external: true
# --- nginx.conf
server {
    listen 8080;
    location /healthz { return 200 "ok\n"; }
    location / { proxy_pass http://api:9000; }
}
version: "3.13"
services:
  api:
    deploy:
      replicas: 3
      update_config:
        parallelism: 1
        delay: 10s
        failure_action: rollback
        monitor: 30s
        order: start-first
      rollback_config:
        parallelism: 0
        order: stop-first
      resources:
        limits:
          memory: "536870912"
        reservations:
          cpus: "0.25"
          memory: "268435456"
      restart_policy:
        condition: any
        delay: 5s
      placement:
        constraints:
          - node.role == worker
        preferences:
          - spread: node.labels.zone
        max_replicas_per_node: 2
    environment:
      DB_HOST: db
      DB_PASSWORD_FILE: /run/secrets/db_password
      DB_USER: shop
    healthcheck:
      test:
        - CMD
        - wget
        - -qO-
        - http://127.0.0.1:9000/health
      interval: 10s
      retries: 3
      start_period: 20s
    image: ghcr.io/acme/shop-api:2.4.1
    networks:
      back: null
      front: null
    secrets:
      - source: db_password
        target: db_password
  db:
    deploy:
      replicas: 1
      update_config:
        order: stop-first
      resources:
        reservations:
          memory: "1073741824"
      placement:
        constraints:
          - node.labels.db == true
    environment:
      POSTGRES_PASSWORD_FILE: /run/secrets/db_password
      POSTGRES_USER: shop
    image: postgres:17
    networks:
      back: null
    secrets:
      - source: db_password
        target: db_password
    volumes:
      - type: volume
        source: pgdata
        target: /var/lib/postgresql/data
  proxy:
    configs:
      - source: nginx_conf
        target: /etc/nginx/conf.d/default.conf
    deploy:
      replicas: 3
      update_config:
        parallelism: 1
        delay: 10s
        failure_action: rollback
        monitor: 30s
        order: start-first
      placement:
        constraints:
          - node.role == worker
        preferences:
          - spread: node.labels.zone
    healthcheck:
      test:
        - CMD
        - wget
        - -qO-
        - http://127.0.0.1:8080/healthz
      interval: 10s
      retries: 3
    image: nginx:1.27-alpine
    networks:
      front: null
    ports:
      - mode: ingress
        target: 8080
        published: 80
        protocol: tcp
  visualizer:
    deploy:
      placement:
        constraints:
          - node.role == manager
    image: dockersamples/visualizer:latest
    ports:
      - mode: ingress
        target: 8080
        published: 8081
        protocol: tcp
    volumes:
      - type: bind
        source: /var/run/docker.sock
        target: /var/run/docker.sock
        read_only: true
networks:
  back:
    driver: overlay
    driver_opts:
      encrypted: "true"
    internal: true
  front:
    driver: overlay
volumes:
  pgdata: {}
secrets:
  db_password:
    name: shop_db_password_v1
    external: true
configs:
  nginx_conf:
    name: shop_nginx_1
    file: /home/ada/demo/nginx.conf
x-update:
  delay: 10s
  failure_action: rollback
  monitor: 30s
  order: start-first
  parallelism: 1

Two things to check in the output: the x-update anchor was copied into proxy and api (and kept as a top-level x-update key that Swarm ignores), and the db service got its own update_config with stop-first. Two database containers on the same data directory, even for a few seconds, would corrupt it. The visualizer is pinned to managers because only managers answer the Swarm API it reads; since manager-b and manager-c are drained, it always runs on manager-a. That's a real trade-off you'll see in step 6.

Step 5: The production override

Production runs more replicas, a stricter memory limit and publishes 443 instead of 80. Following the lesson on stack files, ports that differ by environment would live only in the environment files; here prod adds a port, so the merge appends it:

compose · try it yourself
# $ docker stack config -c stack.yaml -c prod.yaml
# --- stack.yaml
services:
  api:
    image: ghcr.io/acme/shop-api:${API_TAG:-2.4.1}
    deploy:
      replicas: 3
      resources:
        limits: {memory: 512M}
  proxy:
    image: nginx:1.27-alpine
    ports: ["80:8080"]
    deploy:
      replicas: 3
# --- prod.yaml
services:
  api:
    deploy:
      replicas: 6
      resources:
        limits: {memory: 384M}
  proxy:
    ports: ["443:8443"]
version: "3.13"
services:
  api:
    deploy:
      replicas: 6
      resources:
        limits:
          memory: "402653184"
    image: ghcr.io/acme/shop-api:2.4.1
  proxy:
    deploy:
      replicas: 3
    image: nginx:1.27-alpine
    ports:
      - mode: ingress
        target: 8080
        published: 80
        protocol: tcp
      - mode: ingress
        target: 8443
        published: 443
        protocol: tcp

The proxy publishes both 80 and 443 in production, which is what we want here (80 redirects to HTTPS). The api got 6 replicas and the tighter limit, while everything else came from the base file.

Step 6: Fire drill, a node and then a zone fail

Now the interesting part. This model places the services like the scheduler would (constraints, zone spread, max_replicas_per_node, reservations) and then takes nodes away:

python · try it yourself
nodes = {
    "manager-a": {"zone": "a", "role": "manager", "labels": {}, "mem": 4096, "avail": "active"},
    "manager-b": {"zone": "b", "role": "manager", "labels": {}, "mem": 4096, "avail": "drain"},
    "manager-c": {"zone": "c", "role": "manager", "labels": {}, "mem": 4096, "avail": "drain"},
    "worker-a1": {"zone": "a", "role": "worker", "labels": {"db": "true"}, "mem": 4096, "avail": "active"},
    "worker-a2": {"zone": "a", "role": "worker", "labels": {}, "mem": 2048, "avail": "active"},
    "worker-b1": {"zone": "b", "role": "worker", "labels": {}, "mem": 2048, "avail": "active"},
    "worker-b2": {"zone": "b", "role": "worker", "labels": {}, "mem": 2048, "avail": "active"},
    "worker-c1": {"zone": "c", "role": "worker", "labels": {}, "mem": 2048, "avail": "active"},
    "worker-c2": {"zone": "c", "role": "worker", "labels": {}, "mem": 2048, "avail": "active"},
}
services = {   # name: (replicas, eligible(node) -> bool, memory reservation MiB, max per node)
    "db":         (1, lambda n: n["labels"].get("db") == "true", 1024, None),
    "api":        (3, lambda n: n["role"] == "worker", 256, 2),
    "proxy":      (3, lambda n: n["role"] == "worker", 64, None),
    "visualizer": (1, lambda n: n["role"] == "manager", 64, None),
}

def schedule(down):
    free = {k: v["mem"] for k, v in nodes.items()}
    placed = {k: [] for k in nodes}
    result = {}
    for svc, (replicas, ok, mem, per_node) in services.items():
        result[svc] = []
        for _ in range(replicas):
            cands = [k for k, n in nodes.items()
                     if k not in down and n["avail"] == "active" and ok(n) and free[k] >= mem
                     and (per_node is None or placed[k].count(svc) < per_node)]
            if not cands:
                result[svc].append("PENDING")
                continue
            def zone_load(k):
                return sum(placed[x].count(svc) for x in nodes if nodes[x]["zone"] == nodes[k]["zone"])
            best = min(cands, key=lambda k: (zone_load(k), placed[k].count(svc), k))
            placed[best].append(svc)
            free[best] -= mem
            result[svc].append(best)
    return result

def drill(title, down):
    print(f"== {title}")
    managers_up = sum(1 for k, n in nodes.items() if n["role"] == "manager" and k not in down)
    print(f"   managers up: {managers_up}/3 -> {'quorum OK' if managers_up >= 2 else 'NO QUORUM'}")
    for svc, where in schedule(down).items():
        running = sum(w != "PENDING" for w in where)
        flag = "" if running == len(where) else "   <-- degraded"
        print(f"   {svc:<10} {running}/{len(where)} {where}{flag}")

drill("all nodes up", set())
drill("worker-b1 fails", {"worker-b1"})
drill("zone a fails", {"manager-a", "worker-a1", "worker-a2"})
== all nodes up
   managers up: 3/3 -> quorum OK
   db         1/1 ['worker-a1']
   api        3/3 ['worker-a1', 'worker-b1', 'worker-c1']
   proxy      3/3 ['worker-a1', 'worker-b1', 'worker-c1']
   visualizer 1/1 ['manager-a']
== worker-b1 fails
   managers up: 3/3 -> quorum OK
   db         1/1 ['worker-a1']
   api        3/3 ['worker-a1', 'worker-b2', 'worker-c1']
   proxy      3/3 ['worker-a1', 'worker-b2', 'worker-c1']
   visualizer 1/1 ['manager-a']
== zone a fails
   managers up: 2/3 -> quorum OK
   db         0/1 ['PENDING']   <-- degraded
   api        3/3 ['worker-b1', 'worker-c1', 'worker-b2']
   proxy      3/3 ['worker-b1', 'worker-c1', 'worker-b2']
   visualizer 0/1 ['PENDING']   <-- degraded

Read the drill results carefully:

  • One worker down: everything is rescheduled within the spread rules, nothing is lost.
  • Zone a down: the swarm keeps quorum (2 of 3 managers) and the stateless services fill up the other zones. But two single points of failure show up: db is Pending because the only node with db=true is gone (and its data with it), and visualizer is Pending because the only active manager was in zone a.

That's the honest result of this design. The visualizer is a nice-to-have; the database is not. Options, from the Volumes and High Availability lessons: a managed database outside the swarm, a replicated PostgreSQL setup (a primary plus a streaming replica in another zone, promoted on failure), or storage that can move between zones. Whatever you choose, back up the database separately: the swarm backup doesn't contain volume data (Backup & Restore).

Step 7: A bad release rolls itself back

Finally, check the update policy: version 2.5.0 of the api fails its healthcheck. With parallelism: 1, order: start-first, monitor: 30s and failure_action: rollback, how many users are affected?

python · try it yourself
replicas = ["2.4.1"] * 3
healthy_versions = {"2.4.1"}

def update(new):
    for i in range(len(replicas)):
        print(f"start new task {new} next to slot {i + 1} (start-first): ", end="")
        if new not in healthy_versions:
            print("unhealthy within monitor window -> failure_action: rollback")
            print(f"rollback: all slots back to {replicas[0]} at once (rollback parallelism 0)")
            return False
        replicas[i] = new
        print(f"healthy, old task stopped -> {replicas}")
    return True

ok = update("2.5.0")
print("result:", "updated" if ok else "rolled back", replicas)
healthy_versions.add("2.5.1")
print()
ok = update("2.5.1")
print("result:", "updated" if ok else "rolled back", replicas)
start new task 2.5.0 next to slot 1 (start-first): unhealthy within monitor window -> failure_action: rollback
rollback: all slots back to 2.4.1 at once (rollback parallelism 0)
result: rolled back ['2.4.1', '2.4.1', '2.4.1']

start new task 2.5.1 next to slot 1 (start-first): healthy, old task stopped -> ['2.5.1', '2.4.1', '2.4.1']
start new task 2.5.1 next to slot 2 (start-first): healthy, old task stopped -> ['2.5.1', '2.5.1', '2.4.1']
start new task 2.5.1 next to slot 3 (start-first): healthy, old task stopped -> ['2.5.1', '2.5.1', '2.5.1']
result: updated ['2.5.1', '2.5.1', '2.5.1']

Because of start-first, the broken 2.5.0 task never replaced a working one: all three old tasks kept serving while the new one failed its healthcheck, and the update was rolled back. The fixed 2.5.1 then rolled out one slot at a time (Rolling Updates, Rollbacks).

Step 8: Deploy it for real

bash
#!/bin/sh
# deploy.sh
set -eu
export API_TAG="${API_TAG:?set API_TAG}" NGINX_CONF_REV="${NGINX_CONF_REV:-1}" DB_PASSWORD_REV="${DB_PASSWORD_REV:-v1}"
docker stack config -c stack.yaml -c prod.yaml > /dev/null          # fail fast on errors
docker stack deploy --with-registry-auth --prune --detach=false \
  -c stack.yaml -c prod.yaml shop
docker stack services shop
bash
$ API_TAG=2.4.1 ./deploy.sh
...
ID             NAME              MODE         REPLICAS   IMAGE                             PORTS
4n1x8c2v7b0m   shop_api          replicated   6/6        ghcr.io/acme/shop-api:2.4.1
q7w2e5r8t1y4   shop_db           replicated   1/1        postgres:17
z0x3c6v9b2n5   shop_proxy        replicated   3/3        nginx:1.27-alpine                 *:80->8080/tcp, *:443->8443/tcp
m8k5j2h9g6f3   shop_visualizer   replicated   1/1        dockersamples/visualizer:latest   *:8081->8080/tcp

(sample output.) Then repeat the drills on the real cluster: docker node update --availability drain worker-b1, watch the visualizer on port 8081 and docker service ps shop_api, then bring the node back and rebalance with docker service update --force shop_api.

Where to go next

Test yourself

Why does the db service use update_config.order: stop-first while the api uses start-first?

  1. stop-first is faster
  2. Two PostgreSQL containers must never use the same data directory at the same time
  3. start-first is not allowed for databases
  4. Because db has only one replica, start-first is impossible

In the zone-a drill, why does db stay Pending even though other workers have free memory?

  1. The swarm lost quorum
  2. Its placement constraint node.labels.db == true matches only worker-a1, which is down
  3. The secret is missing
  4. The back network is internal

With order: start-first and failure_action: rollback, what happens when the first new task of a broken release fails its healthcheck?

  1. One old task is already gone, so capacity drops
  2. The old tasks are still running; the update is rolled back
  3. All tasks are replaced anyway
  4. The service is removed