TExcelTAD
Home › Docker Compose › From Compose to Swarm

From Compose to Swarm

At some point one server isn't enough: you need a second machine for capacity, or simply so the app survives when the first one reboots. Docker Swarm is the smallest step from Compose to a cluster. It's built into the Docker Engine, and it deploys the same YAML format as a stack: docker stack deploy -c compose.yaml shop. Services become Swarm services with replicas spread over the nodes, networks become overlay networks, and the deploy: section you met in Scaling & Resources finally does everything it promises.

But "the same format" isn't "the same features". Swarm reads the Compose file with its own parser (the classic version 3 schema), which rejects some newer Compose keys and silently ignores others. This lesson shows what carries over, what doesn't, and a reliable way to convert. The Swarm course covers the cluster side in depth, starting at Swarm Intro and Stacks.

Compose vs Swarm at a glance

text
 Compose (one host)                         Swarm (a cluster)
 ┌──────────── host ────────────┐           ┌─ manager ─┐  ┌─ worker ─┐  ┌─ worker ─┐
 │ demo-api-1  demo-api-2       │           │ api.1     │  │ api.2    │  │ api.3    │
 │ demo-db-1                    │           │ db.1      │  │          │  │          │
 │ bridge network demo_default  │           └─────┬─────┘  └────┬─────┘  └────┬─────┘
 └──────────────────────────────┘                 └── overlay network shop_default ─┘
 docker compose up -d                       docker stack deploy -c compose.yaml shop

Checking a file with docker stack config

docker stack config renders a file the way docker stack deploy would read it, without deploying (and without needing a swarm). It's the stack counterpart of docker compose config:

compose · try it yourself
# $ docker stack config -c compose.yaml
services:
  api:
    image: ghcr.io/acme/api:${API_TAG:-3.1}
    build: .
    container_name: shop-api
    restart: always
    depends_on: [db]
    ports: ["8000:8000"]
    deploy:
      replicas: 3
      update_config: {parallelism: 1, order: start-first}
      resources:
        limits: {memory: 256M}
  db:
    image: postgres:17
    volumes: [pgdata:/var/lib/postgresql/data]

volumes:
  pgdata:
version: "3.13"
services:
  api:
    build:
      context: .
    container_name: shop-api
    depends_on:
      - db
    deploy:
      replicas: 3
      update_config:
        parallelism: 1
        order: start-first
      resources:
        limits:
          memory: "268435456"
    image: ghcr.io/acme/api:3.1
    ports:
      - mode: ingress
        target: 8000
        published: 8000
        protocol: tcp
    restart: always
  db:
    image: postgres:17
    volumes:
      - type: volume
        source: pgdata
        target: /var/lib/postgresql/data
volumes:
  pgdata: {}

The output looks different from docker compose config: a version: "3.13" header, no project prefixes, no default network, no volume: {} details. The file is accepted, but several keys in it won't do anything in a swarm. When you deploy it, Docker tells you (sample output):

bash
$ docker stack deploy -c compose.yaml shop
Ignoring unsupported options: build, restart

Ignoring deprecated options:

container_name: Setting the container name is not supported.

Creating network shop_default
Creating service shop_api
Creating service shop_db

depends_on is accepted but has no effect either: Swarm starts services in no particular order and relies on restarts until dependencies are reachable.

Keys that Swarm rejects

Newer Compose-only features fail validation outright:

compose · try it yourself
# $ docker stack config -c compose.yaml
# $ docker stack config -c depends.yaml
# $ docker stack config -c named.yaml
services:
  adminer:
    image: adminer:5
    profiles: [debug]

# --- depends.yaml
services:
  api:
    image: ghcr.io/acme/api:3.1
    depends_on:
      db: {condition: service_healthy}
  db:
    image: postgres:17

# --- named.yaml
name: shop
services:
  api:
    image: ghcr.io/acme/api:3.1
$ docker stack config -c compose.yaml
services.adminer: additional property 'profiles' is not allowed
$ docker stack config -c depends.yaml
services.api.depends_on: must be a list
$ docker stack config -c named.yaml
(root): additional property 'name' is not allowed

The full picture:

Compose feature In a stack What to do
deploy.replicas, resources, update_config, placement used (this is where they shine) keep
image, environment, ports, volumes, networks, healthcheck, secrets, configs (file) used keep
build ignored build and push in CI, reference the image
restart ignored use deploy.restart_policy
container_name ignored names are stack_service.N.taskid
depends_on (list) ignored make services retry; use healthchecks
depends_on with conditions rejected flatten to a list or remove
profiles, develop, top-level name, include rejected render with docker compose config first, or keep in dev-only files
configs.content rejected use file: or an external config
extends, !reset, !override not understood render with docker compose config first

Merging stack files

Like docker compose -f, you can pass several -c files; later files override earlier ones:

compose · try it yourself
# $ docker stack config -c compose.yaml -c stack.prod.yaml
services:
  api:
    image: ghcr.io/acme/api:3.1
    environment:
      LOG_LEVEL: info

# --- stack.prod.yaml
services:
  api:
    environment:
      LOG_LEVEL: warn
    deploy:
      replicas: 4
      placement:
        constraints: ["node.role == worker"]
version: "3.13"
services:
  api:
    deploy:
      replicas: 4
      placement:
        constraints:
          - node.role == worker
    environment:
      LOG_LEVEL: warn
    image: ghcr.io/acme/api:3.1

A conversion workflow

The robust approach is to let Compose do what only Compose can (overrides, extends, include, profiles, !reset), then hand Swarm a plain, flat file:

bash
$ docker compose -f compose.yaml -f compose.prod.yaml config --no-interpolate > stack.yaml   # flatten
$ docker stack config -c stack.yaml > /dev/null && echo "stack file OK"                     # validate
$ docker stack deploy -c stack.yaml --with-registry-auth --detach=false shop                  # deploy

You'll usually still need a small edit pass: remove the top-level name: and depends_on conditions, and move restart: into deploy.restart_policy. A model of that conversion step:

python · try it yourself
import yaml

COMPOSE = """
name: shop
services:
  api:
    image: ghcr.io/acme/api:3.1
    build: {context: .}
    restart: unless-stopped
    container_name: shop-api
    depends_on:
      db: {condition: service_healthy, required: true}
    deploy: {replicas: 3}
  db:
    image: postgres:17
    restart: always
  adminer:
    image: adminer:5
    profiles: [debug]
"""

RESTART = {"always": "any", "unless-stopped": "any", "on-failure": "on-failure", "no": "none"}

def to_stack(spec):
    notes = []
    if spec.pop("name", None):
        notes.append("removed top-level name (stack name comes from the deploy command)")
    out = {}
    for svc_name, svc in spec["services"].items():
        if "profiles" in svc:
            notes.append(f"{svc_name}: dropped (profiled service, not for production)")
            continue
        svc = dict(svc)
        for key in ("build", "container_name"):
            if svc.pop(key, None) is not None:
                notes.append(f"{svc_name}: removed {key}")
        if "restart" in svc:
            cond = RESTART[svc.pop("restart")]
            svc.setdefault("deploy", {})["restart_policy"] = {"condition": cond}
            notes.append(f"{svc_name}: restart -> deploy.restart_policy.condition={cond}")
        if isinstance(svc.get("depends_on"), dict):
            svc["depends_on"] = list(svc["depends_on"])
            notes.append(f"{svc_name}: depends_on conditions flattened (Swarm ignores order)")
        out[svc_name] = svc
    return {"services": out}, notes

stack, notes = to_stack(yaml.safe_load(COMPOSE))
for n in notes:
    print("-", n)
print()
print(yaml.safe_dump(stack, sort_keys=False), end="")
- removed top-level name (stack name comes from the deploy command)
- api: removed build
- api: removed container_name
- api: restart -> deploy.restart_policy.condition=any
- api: depends_on conditions flattened (Swarm ignores order)
- db: restart -> deploy.restart_policy.condition=any
- adminer: dropped (profiled service, not for production)

services:
  api:
    image: ghcr.io/acme/api:3.1
    depends_on:
    - db
    deploy:
      replicas: 3
      restart_policy:
        condition: any
  db:
    image: postgres:17
    deploy:
      restart_policy:
        condition: any

What you gain

Once it's running as a stack, the same file gives you rolling updates with automatic rollback, services rescheduled when a node dies, a routing mesh that answers on the published port of every node, encrypted secrets, and docker service scale api=6 across machines. See Rolling Updates, The Routing Mesh and Stack Files & deploy.

What you must now handle yourself: volumes are per node. A pgdata volume on node 1 doesn't follow the database to node 2. Pin stateful services with placement constraints or use a volume driver backed by shared storage (Volumes in a Swarm).

Learn more: Stacks · Stack Variables & docker stack config · Swarm vs Kubernetes · From Compose to Kubernetes

Test yourself

What happens to build: when a compose file is deployed with docker stack deploy?

  1. Swarm builds the image on each node
  2. It is ignored ('Ignoring unsupported options: build'); the image must already be in a registry
  3. The deploy fails
  4. The manager builds it once

Which of these makes docker stack config fail?

  1. deploy.replicas: 3
  2. depends_on: [db]
  3. profiles: [debug]
  4. restart: always

How do you use Compose-only features (extends, include, overrides with !reset) with Swarm?

  1. Swarm supports them natively
  2. Render the final file with docker compose config, then validate it with docker stack config and deploy that
  3. Use --compat
  4. You can't