Creating a Swarm
Creating a swarm takes two commands: docker swarm init on the first machine, then docker swarm join on each of the others. This lesson walks through both, explains the join tokens and the address options, and shows how to plan where managers go so that the cluster survives the failures you care about.
What you need
- Two or more machines (VMs, cloud instances, small boards) with Docker Engine installed. A single machine works too: a one-node swarm is the easiest way to practise
docker serviceanddocker stackcommands on a laptop. - Network connectivity between them on 2377/tcp, 7946/tcp+udp and 4789/udp (see Swarm Architecture).
- Stable IP addresses for the managers. Workers find managers by address, so a manager whose IP changes after a reboot causes trouble.
The examples below use this lab (sample hosts and addresses):
10.0.0.11 manager-1 10.0.0.21 worker-1
10.0.0.12 manager-2 10.0.0.22 worker-2
10.0.0.13 manager-3docker swarm init
On the first manager:
$ 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
To add a manager to this swarm, run 'docker swarm join-token manager' and follow the instructions.In one step this node created a root CA and its own certificate, started a Raft store with itself as the only member (and therefore the leader), created the ingress overlay network for the routing mesh, and generated two join tokens.
The options you are most likely to need:
| Option | What it does |
|---|---|
--advertise-addr <ip|iface>[:port] |
the address other nodes use to reach this manager. Required when the machine has several addresses. |
--listen-addr <ip>[:port] |
where to listen for cluster traffic (default 0.0.0.0:2377) |
--data-path-addr <ip|iface> |
send overlay (container) traffic over a different interface than control traffic |
--default-addr-pool 10.20.0.0/16 |
the range overlay subnets are taken from, if the default 10.0.0.0/8 clashes with your network |
--autolock |
encrypt the managers' Raft keys with a key you must supply after each restart (Swarm Security) |
--task-history-limit 5 |
how many old tasks per slot are kept for docker service ps |
--cert-expiry 2160h0m0s |
validity of node certificates (90 days by default); they renew automatically |
Note: the default address pool clashing with the hosts' own
10.xnetwork is a common surprise: services on overlays then cannot reach parts of your LAN. Choose--default-addr-poolup front; it cannot be changed without recreating the swarm.
Join tokens
There are two tokens, one per role. Anyone holding the manager token can add a node that gets a full copy of the cluster state and its secrets, so treat it like a root password. Print them on any manager:
$ docker swarm join-token manager
To add a manager to this swarm, run the following command:
docker swarm join --token SWMTKN-1-3pu6hszjas19xyp7ghgosyx9k8atbfcr8p2is99znpy26u2lkl-7p73s1dx5in4tatdymyhg9hu2 10.0.0.11:2377
$ docker swarm join-token -q worker
SWMTKN-1-3pu6hszjas19xyp7ghgosyx9k8atbfcr8p2is99znpy26u2lkl-1awxwuwd3z9j1z3puu7rcgdbxA token has two parts after the SWMTKN-1- prefix: a fingerprint of the swarm's root CA and a secret for the role. The fingerprint is what makes joining safe on an untrusted network: the new node checks that the manager it reached presents a CA with that fingerprint before trusting it, so an impostor at the manager's address cannot capture the node. The secret proves to the manager that the node is allowed in, and with which role.
import hashlib
def fingerprint(ca_pem):
return hashlib.sha256(ca_pem.encode()).hexdigest()[:20]
real_ca = "-----BEGIN CERTIFICATE----- swarm-root-ca-2026 -----END CERTIFICATE-----"
fake_ca = "-----BEGIN CERTIFICATE----- attacker-ca -----END CERTIFICATE-----"
secrets = {"worker": "1awxwuwd3z9j", "manager": "7p73s1dx5in4"}
def make_token(role):
return f"SWMTKN-1-{fingerprint(real_ca)}-{secrets[role]}"
def join(token, presented_ca):
_, _, ca_hash, secret = token.split("-")
if fingerprint(presented_ca) != ca_hash:
return "refused: the remote CA does not match the token (possible man-in-the-middle)"
role = next((r for r, s in secrets.items() if s == secret), None)
if role is None:
return "refused by manager: invalid join token"
return f"joined as {role}, got a node certificate signed by the swarm CA"
worker_token = make_token("worker")
print(worker_token)
print("1:", join(worker_token, real_ca))
print("2:", join(make_token("manager"), real_ca))
print("3:", join(worker_token, fake_ca))
secrets["worker"] = "q9zk2m4n8b1c" # docker swarm join-token --rotate worker
print("4:", join(worker_token, real_ca))SWMTKN-1-e7e681be2edf204f4a7f-1awxwuwd3z9j
1: joined as worker, got a node certificate signed by the swarm CA
2: joined as manager, got a node certificate signed by the swarm CA
3: refused: the remote CA does not match the token (possible man-in-the-middle)
4: refused by manager: invalid join token
The last line shows rotation: docker swarm join-token --rotate worker replaces the secret, so leaked copies of the old token stop working. Nodes that already joined are not affected; tokens are only checked at join time.
docker swarm join
On every other machine, paste the matching command. Add --advertise-addr on nodes with several interfaces:
manager-2$ docker swarm join --advertise-addr 10.0.0.12 --token SWMTKN-1-3pu6...-7p73s1dx5in4tatdymyhg9hu2 10.0.0.11:2377
This node joined a swarm as a manager.
worker-1$ docker swarm join --token SWMTKN-1-3pu6...-1awxwuwd3z9j1z3puu7rcgdbx 10.0.0.11:2377
This node joined a swarm as a worker.Back on a manager, the whole cluster is visible (sample output):
$ docker node ls
ID HOSTNAME STATUS AVAILABILITY MANAGER STATUS ENGINE VERSION
k3x9v2m1q8w7e6r5t4y3u2i1o * manager-1 Ready Active Leader 29.0.1
m8n7b6v5c4x3z2l1k0j9h8g7f manager-2 Ready Active Reachable 29.0.1
q1w2e3r4t5y6u7i8o9p0a1s2d manager-3 Ready Active Reachable 29.0.1
z9x8c7v6b5n4m3l2k1j0h9g8f worker-1 Ready Active 29.0.1
a1b2c3d4e5f6g7h8i9j0k1l2m worker-2 Ready Active 29.0.1The * marks the node you are connected to. An empty MANAGER STATUS means "worker". docker info on any node shows Swarm: active, the node's role and, on managers, the cluster ID and manager addresses.
Planning manager placement
Three managers are only as good as their independence. If two of them share a rack, a power strip or a cloud availability zone, a single outage removes the majority. A quick model: spread managers over zones and see which single-zone failure the cluster survives.
layouts = {
"3 managers, 2 zones (2+1)": {"zone-a": 2, "zone-b": 1},
"3 managers, 3 zones (1+1+1)": {"zone-a": 1, "zone-b": 1, "zone-c": 1},
"5 managers, 3 zones (2+2+1)": {"zone-a": 2, "zone-b": 2, "zone-c": 1},
"5 managers, 2 zones (3+2)": {"zone-a": 3, "zone-b": 2},
}
for name, zones in layouts.items():
total = sum(zones.values())
quorum = total // 2 + 1
results = []
for down, lost in zones.items():
alive = total - lost
results.append(f"{down} down: {'ok' if alive >= quorum else 'NO QUORUM'}")
print(f"{name:<28} quorum {quorum} | " + ", ".join(results))3 managers, 2 zones (2+1) quorum 2 | zone-a down: NO QUORUM, zone-b down: ok
3 managers, 3 zones (1+1+1) quorum 2 | zone-a down: ok, zone-b down: ok, zone-c down: ok
5 managers, 3 zones (2+2+1) quorum 3 | zone-a down: ok, zone-b down: ok, zone-c down: ok
5 managers, 2 zones (3+2) quorum 3 | zone-a down: NO QUORUM, zone-b down: ok
With two zones, one of them always holds the majority, and losing that zone freezes the swarm. Three zones (or three independent failure domains of any kind) are needed to survive the loss of any one of them. High Availability goes further.
Leaving and removing
| Command | Where | Effect |
|---|---|---|
docker swarm leave |
on a worker | the node leaves; its tasks are rescheduled elsewhere; it shows as Down until removed |
docker node rm worker-2 |
on a manager | removes a node that has left (add --force for a node that is unreachable) |
docker node demote manager-3, then leave |
on a manager | the safe way to retire a manager: it stops being a Raft member first |
docker swarm leave --force |
on a manager | leaves without demoting; on the last manager it destroys the swarm |
Avoid leave --force on a manager in a healthy cluster: the cluster still counts it as a member, so the quorum math now includes a manager that will never come back. Demote first.
Learn more: Managing Nodes · Swarm Security · Kubernetes local clusters
Test yourself
What does the first part of a swarm join token (after SWMTKN-1-) protect against?
- Expired certificates
- Joining an impostor: the new node checks the manager's root CA against this fingerprint
- Running out of IP addresses
- Too many managers
A worker token leaked in a chat log. What should you do?
- Recreate the swarm
- Run
docker swarm join-token --rotate worker; existing nodes are unaffected - Remove all workers
- Nothing, tokens expire after an hour
Three managers are placed as 2 in zone A and 1 in zone B. Zone A goes down. What happens?
- Nothing, one manager is enough
- The swarm loses quorum: running containers continue, but no changes or rescheduling are possible
- Zone B elects two new managers automatically
- All containers stop