Opscraft
Docker Swarm · Lesson 5 of 10 · 3 min read

Stacks: compose files for the cluster

Deploying a stack

A stack is a set of services, networks, volumes, secrets and configs defined in a compose-format file and deployed together:

docker stack deploy -c stack.yml shop --with-registry-auth
docker stack ls
docker stack services shop
docker stack ps shop
docker stack rm shop
  • Re-running stack deploy with a changed file updates the stack (only changed services roll).
  • --with-registry-auth forwards your registry credentials (e.g. ECR login) to the nodes so they can pull private images.
  • Resources are prefixed with the stack name: shop_api, shop_backend.
  • Stacks need images pre-built and pushed — build: is ignored.
Enlarge diagramstack.yamlCompose format + deploy:docker stack deployshop_api3 replicasshop_dbpinned to the ssd nodeshop_backendoverlay networkSwarm ignores depends_on and build:, so images must already be in a registry.
Figure 1. A stack is a Compose file deployed to the whole cluster. The deploy section adds replicas, placement, resources and update rules.
Swipe sideways to see all of it, or tap to open it full screen.

The deploy section

services:
  api:
    image: 123456789012.dkr.ecr.ap-south-1.amazonaws.com/shop-api:3f9c2a1
    networks: [backend]
    secrets: [db_password]
    healthcheck:
      test: ["CMD", "wget", "-qO-", "http://localhost:3000/health"]
      interval: 10s
      retries: 3
      start_period: 20s
    deploy:
      mode: replicated
      replicas: 4
      placement:
        constraints: [node.role == worker]
        preferences: [{ spread: node.labels.zone }]
        max_replicas_per_node: 2
      resources:
        reservations: { cpus: "0.5", memory: 256M }
        limits:       { cpus: "1.0", memory: 512M }
      restart_policy:
        condition: on-failure
        delay: 5s
        max_attempts: 3
        window: 60s
      update_config:
        parallelism: 1
        delay: 10s
        order: start-first
        failure_action: rollback
        monitor: 30s
        max_failure_ratio: 0.1
      rollback_config:
        parallelism: 2
        order: stop-first
networks:
  backend: { driver: overlay }
secrets:
  db_password: { external: true }

Compose keys ignored by stack deploy: build, depends_on, container_name, links, restart (use deploy.restart_policy), and some others. Swarm has no start ordering — services must retry connections.