TExcelTAD
Home › Docker Swarm › Swarm Intro

Swarm Intro

Docker Swarm mode is the container orchestrator that ships inside Docker Engine. The same dockerd that runs your containers on a laptop can join other engines to form a swarm: a cluster that keeps a declared number of containers running across several machines, replaces them when they crash or when a machine disappears, spreads them out, updates them a few at a time and load-balances traffic between them.

There is nothing extra to install. If a machine has Docker, it can be a swarm node. That is Swarm's main selling point: you go from docker compose up on one host to a highly available service on three hosts with a couple of commands and the Compose file format you already know.

Note: "Docker Swarm" once meant a separate product (the old standalone Swarm container, now retired). Everything in this course is Swarm mode, built into the engine since Docker 1.12 and powered by the open-source SwarmKit library. It is still maintained and still ships with Docker Engine 29.

Where Swarm fits

You probably know at least one of its neighbours:

Docker Compose Docker Swarm Kubernetes
Scope one host a cluster of hosts a cluster of hosts
Installed with Docker yes (plugin) yes (built into the engine) no, a separate platform
Unit you deploy containers of a project services made of tasks Pods managed by Deployments, StatefulSets…
File format compose.yaml the same format, using the deploy: key its own manifests (YAML), Helm, Kustomize
Self-healing across machines no yes yes
Rolling updates / rollback recreate built in built in
Ecosystem dev tooling small, stable enormous
Learning curve gentle gentle steep

A short way to remember it: Compose runs an app on one machine, Swarm runs the same app on many machines with almost no new concepts, and Kubernetes is the general-purpose platform with an ecosystem for everything (and the complexity that comes with it). The Docker orchestration overview compares the options in one page; the Compose course covers the single-host story in depth and the Kubernetes course the other end of the scale.

The vocabulary

Term Meaning
node one Docker Engine that is part of the swarm (a VM, a server, a Raspberry Pi)
manager a node that stores the cluster state and makes decisions; managers agree with each other through Raft
worker a node that only runs the containers it is given
service the thing you declare: "run image X, 3 copies, on port 8080, with these limits"
task one slot of a service: a container plus the scheduling decision of where it runs
stack a group of services, networks, configs and secrets deployed together from a Compose file

The key shift from plain Docker is that you stop starting containers. You create a service, the swarm turns it into tasks, assigns each task to a node, and each node starts a container for its task. If the container dies, the task fails and the swarm creates a new one. You manage the goal, the swarm manages the containers.

text
         you: "3 replicas of web:1.4"
                      |
                      v
   +-------------------------------------+
   |  managers (Raft)   desired state    |
   |  service web: replicas=3            |
   +-------------------------------------+
        |               |              |
     task web.1      task web.2     task web.3
        v               v              v
    [ node-1 ]      [ node-2 ]     [ node-3 ]
    container       container      container

A first look

On a real cluster, a first session looks like this (sample output; IDs, hostnames and addresses vary):

bash
$ docker swarm init --advertise-addr 10.0.0.11
Swarm initialized: current node (k3x9v2m1q8w7e6r5t4y3u2i1o) is now a manager.

To add a worker to this swarm, run the following command:

    docker swarm join --token SWMTKN-1-3pu6hszjas19xyp7ghgosyx9k8atbfcr8p2is99znpy26u2lkl-1awxwuwd3z9j1z3puu7rcgdbx 10.0.0.11:2377

$ docker service create --name web --replicas 3 --publish 8080:80 nginx:1.27-alpine
p4d0n1xq8hcz2kxw9gbyc7e3m
overall progress: 3 out of 3 tasks
1/3: running   [==================================================>]
2/3: running   [==================================================>]
3/3: running   [==================================================>]
verify: Service p4d0n1xq8hcz2kxw9gbyc7e3m converged

$ docker service ls
ID             NAME      MODE         REPLICAS   IMAGE               PORTS
p4d0n1xq8hcz   web       replicated   3/3        nginx:1.27-alpine   *:8080->80/tcp

Most of the time you will not type docker service create but deploy a stack file, which is a Compose file with deploy: settings. Here is a small one, passed through the real docker stack config, the command that prints what docker stack deploy would send to the swarm after reading and interpolating the file:

compose · try it yourself
# $ docker stack config -c stack.yaml
# --- stack.yaml
services:
  web:
    image: nginx:1.27-alpine
    ports:
      - "8080:80"
    deploy:
      replicas: 3
      update_config:
        parallelism: 1
        delay: 10s
      restart_policy:
        condition: on-failure
version: "3.13"
services:
  web:
    deploy:
      replicas: 3
      update_config:
        parallelism: 1
        delay: 10s
      restart_policy:
        condition: on-failure
    image: nginx:1.27-alpine
    ports:
      - mode: ingress
        target: 80
        published: 8080
        protocol: tcp

Two things to notice: Swarm writes the port in its long form with mode: ingress (published on every node through the routing mesh), and it adds a version: "3.13" line, because the stack command still uses the older Compose file schema internally. You can ignore that line.

How this course runs things

A browser cannot host a cluster of Docker engines, so this course uses three kinds of examples, and each is labelled honestly:

  1. CLI sessions (docker swarm …, docker node …, docker service …) are sample output in plain code blocks. They show realistic output of current Docker, but IDs, times and hostnames will differ on your machines.
  2. Stack files in "Try it yourself" blocks are checked with the real docker stack config: the output was produced by Docker, including its validation errors. Edit the file and the saved output is what Docker printed for the original.
  3. Python models show how the cluster decides: how the scheduler spreads tasks, what happens when a node fails, how a rolling update proceeds. They are simplified, deterministic models, but they follow the same rules as SwarmKit.

Here is the idea at the heart of every orchestrator, and of every model in this course: a loop compares the desired state with what actually runs and closes the gap.

python · try it yourself
replicas = 3
nodes = {"node-1": [], "node-2": [], "node-3": []}

def reconcile(step):
    # every slot 1..replicas must have a running task somewhere
    running = {t for tasks in nodes.values() for t in tasks}
    actions = []
    for slot in range(1, replicas + 1):
        task = f"web.{slot}"
        if task in running:
            continue
        # place the new task on the node with the fewest tasks (ties: by name)
        target = min(nodes, key=lambda n: (len(nodes[n]), n))
        nodes[target].append(task)
        actions.append(f"start {task} on {target}")
    print(f"{step}: {actions or 'nothing to do'}")

reconcile("first run")
reconcile("second run")
lost = nodes.pop("node-2")          # node-2 loses power
print("node-2 down, lost", lost)
reconcile("after failure")
print(nodes)
first run: ['start web.1 on node-1', 'start web.2 on node-2', 'start web.3 on node-3']
second run: nothing to do
node-2 down, lost ['web.2']
after failure: ['start web.2 on node-1']
{'node-1': ['web.1', 'web.2'], 'node-3': ['web.3']}

The task on the failed node is not "moved": a new task for the same slot (web.2) is created on a healthy node; the old one stays in the task history. When node-2 comes back, Swarm does not move anything back to it automatically; we will see why in Managing Nodes.

When to choose Swarm

Swarm is a good fit when:

  • you already use Compose and want several hosts, zero-downtime updates and automatic recovery;
  • the team is small and does not want to run a platform (no add-ons, no control-plane upgrades to plan);
  • clusters are modest: a handful to a few dozen nodes.

Pick Kubernetes when you need its ecosystem (operators, service meshes, autoscalers, managed offerings everywhere) or many teams deploying onto shared infrastructure. The last lesson of this course, Swarm vs Kubernetes, goes into detail, and From Compose & Swarm shows the migration path.

Learn more: Swarm Architecture · Compose to Swarm · Orchestration overview

Test yourself

What do you need to install to use Swarm mode on a machine that already runs Docker Engine?

  1. The Swarm plugin
  2. Kubernetes
  3. Nothing: Swarm mode is built into Docker Engine
  4. The standalone swarm container

In Swarm, what is a task?

  1. A cron job
  2. One slot of a service: a container plus the decision of which node runs it
  3. A Compose project
  4. A manager node

A node running one replica of a 3-replica service fails. What does Swarm do?

  1. Waits for the node to return
  2. Moves the stopped container to another node
  3. Creates a new task on a healthy node so that 3 replicas run again
  4. Lowers the service to 2 replicas