Swarm Architecture
A swarm is a group of Docker engines with two jobs: some of them decide (managers) and all of them can run containers (workers). This lesson looks at what runs inside each kind of node, how managers agree on the cluster state, how a docker service create turns into containers, and which network ports the nodes need between them.
Managers and workers
docker CLI / stack deploy (talks to any manager)
|
+--------------------------+---------------------------+
| manager-1 (Leader) manager-2 manager-3 |
| [Raft log + state] <-> [Raft copy] <-> [Raft copy] |
+-----------+-------------------+-------------------+---+
| task assignments (gRPC, mutual TLS) |
+-------+--------+ +--------+-------+ +-----+----------+
| worker-1 | | worker-2 | | worker-3 |
| agent+executor | | agent+executor | | agent+executor |
| containers | | containers | | containers |
+----------------+ +----------------+ +----------------+| Manager | Worker | |
|---|---|---|
| Stores the cluster state | yes (a full copy of the Raft log) | no |
Accepts docker service/node/stack commands |
yes | no ("This node is not a swarm manager") |
| Runs containers | yes, by default | yes |
| Takes part in leader election | yes | no |
| How many | 1, 3, 5 or 7 (odd numbers) | as many as you like |
A manager is also a worker: unless you drain it (see Managing Nodes), the scheduler places tasks on managers too. In production you usually keep managers free of application work so that a busy container cannot starve the control plane.
Raft: one state, many copies
All cluster state (nodes, services, tasks, networks, secrets, configs) lives in a replicated log maintained with the Raft consensus algorithm. One manager is the leader: it accepts every change, appends it to its log and replicates it to the other managers. A change counts as committed once a majority (the quorum) of managers has stored it. Commands sent to a follower are forwarded to the leader transparently.
If the leader disappears, the remaining managers notice the missing heartbeats and elect a new leader, provided a majority of managers is still reachable. Because a majority is needed, the number of managers decides how many failures the cluster survives:
print(f"{'managers':>8} {'quorum':>7} {'can lose':>9}")
for managers in range(1, 8):
quorum = managers // 2 + 1
tolerated = managers - quorum
note = " <- even: no gain over " + str(managers - 1) if managers % 2 == 0 and managers > 1 else ""
print(f"{managers:>8} {quorum:>7} {tolerated:>9}{note}")managers quorum can lose
1 1 0
2 2 0 <- even: no gain over 1
3 2 1
4 3 1 <- even: no gain over 3
5 3 2
6 4 2 <- even: no gain over 5
7 4 3
Four managers survive one failure, exactly like three, but there is one more machine that can break. That is why manager counts are odd. Docker recommends at most seven: every write must reach a majority, so more managers make writes slower without a useful gain in safety.
What happens when the quorum is lost is important to understand: the containers that are already running keep running, but the swarm is frozen. Nothing can be created, scaled, updated or rescheduled until a majority of managers is back (or you force a new cluster from a survivor). The details, including leader election rounds, are in Raft & Quorum and High Availability.
Inside a manager
A manager is a small pipeline of components. Each one watches the state store, does one job and writes its result back:
| Component | Job |
|---|---|
| API | accepts requests from the CLI (over the Docker socket), validates them, writes the new desired state |
| Orchestrator | compares services with their tasks; creates tasks for missing replicas, removes extra ones, replaces failed ones |
| Allocator | gives new tasks what they need from the cluster: virtual IPs, overlay network addresses |
| Scheduler | picks a node for each unassigned task (filters nodes, then spreads) |
| Dispatcher | holds a session with every node, sends assigned tasks, receives status updates and heartbeats |
Only the leader runs the orchestrator, allocator and scheduler; follower managers serve the API (forwarding writes) and keep their copy of the log. Here is a model of the pipeline handling docker service create --replicas 3:
state = {"services": {}, "tasks": []}
nodes = ["worker-1", "worker-2", "worker-3"]
next_ip = 2
def api(name, image, replicas):
state["services"][name] = {"image": image, "replicas": replicas}
print(f"api: stored service {name} ({image}, replicas={replicas})")
def orchestrator():
for name, svc in state["services"].items():
have = [t for t in state["tasks"] if t["service"] == name]
for slot in range(len(have) + 1, svc["replicas"] + 1):
state["tasks"].append({"id": f"{name}.{slot}", "service": name, "state": "NEW", "node": None, "ip": None})
print(f"orchestrator: created task {name}.{slot} (NEW)")
def allocator():
global next_ip
for t in state["tasks"]:
if t["state"] == "NEW":
t["ip"], t["state"] = f"10.0.1.{next_ip}", "PENDING"
next_ip += 1
print(f"allocator: {t['id']} gets {t['ip']} on the overlay (PENDING)")
def scheduler():
for t in state["tasks"]:
if t["state"] == "PENDING":
load = {n: sum(x["node"] == n for x in state["tasks"]) for n in nodes}
t["node"] = min(nodes, key=lambda n: (load[n], n))
t["state"] = "ASSIGNED"
print(f"scheduler: {t['id']} -> {t['node']} (ASSIGNED)")
def dispatcher():
for t in state["tasks"]:
if t["state"] == "ASSIGNED":
t["state"] = "RUNNING"
print(f"dispatcher: sent {t['id']} to {t['node']}; agent reports RUNNING")
api("web", "nginx:1.27-alpine", 3)
for step in (orchestrator, allocator, scheduler, dispatcher):
step()api: stored service web (nginx:1.27-alpine, replicas=3)
orchestrator: created task web.1 (NEW)
orchestrator: created task web.2 (NEW)
orchestrator: created task web.3 (NEW)
allocator: web.1 gets 10.0.1.2 on the overlay (PENDING)
allocator: web.2 gets 10.0.1.3 on the overlay (PENDING)
allocator: web.3 gets 10.0.1.4 on the overlay (PENDING)
scheduler: web.1 -> worker-1 (ASSIGNED)
scheduler: web.2 -> worker-2 (ASSIGNED)
scheduler: web.3 -> worker-3 (ASSIGNED)
dispatcher: sent web.1 to worker-1; agent reports RUNNING
dispatcher: sent web.2 to worker-2; agent reports RUNNING
dispatcher: sent web.3 to worker-3; agent reports RUNNING
The real components run concurrently and react to change events rather than being called in order, but the hand-offs are the same, and they explain the task states you will see in docker service ps (covered in Services & Tasks).
Inside a worker
Each node runs an agent. It opens a session with a manager's dispatcher, receives the tasks assigned to it, and hands them to the executor, which, for container tasks, is the local Docker Engine creating containers. The agent reports every state change back and sends heartbeats. If a manager does not hear from a node for a while, it marks the node Down and the orchestrator replaces the tasks that were running there.
Workers never see the whole cluster state: they only learn about their own tasks plus the secrets, configs and network details those tasks need. A compromised worker therefore cannot read every secret in the cluster.
Security built in
Swarm turns on mutual TLS between nodes automatically. When you run docker swarm init, the first manager creates a root certificate authority, and every node that joins gets its own certificate signed by it, identifying the node and its role. All control traffic (Raft, dispatcher sessions) is encrypted and authenticated. Certificates are rotated automatically (every 90 days by default). The join tokens, CA rotation and autolock are covered in Creating a Swarm and Swarm Security.
Ports between nodes
Firewalls between nodes must allow:
| Port | Protocol | Used for | Between |
|---|---|---|---|
| 2377 | TCP | cluster management: joining, Raft, dispatcher | nodes and managers |
| 7946 | TCP and UDP | node discovery and gossip of network state | all nodes |
| 4789 | UDP | overlay network data (VXLAN) | all nodes |
| IP protocol 50 (ESP) | encrypted overlay networks (--opt encrypted) |
all nodes |
Plus whatever your services publish (for example 80/443) from clients and load balancers. A cluster where 2377 works but 4789 is blocked looks healthy in docker node ls while containers on different nodes cannot reach each other: a classic first-day problem, revisited in Overlay Networks and Troubleshooting.
Tip: if you know Kubernetes, the mapping is close: managers ≈ the control plane (API server + etcd + scheduler + controllers), the Raft store ≈ etcd, workers ≈ nodes running the kubelet. See Kubernetes Architecture. The big difference is that Swarm packs all of it into the Docker daemon.
Learn more: Creating a Swarm · Raft & Quorum · High Availability
Test yourself
How many manager failures can a swarm with 5 managers survive while keeping quorum?
- 1
- 2
- 3
- 4
The swarm loses quorum. What happens to containers that are already running?
- They are stopped immediately
- They keep running, but the swarm cannot change, scale or reschedule anything until quorum returns
- They are moved to the remaining managers
- They restart in a loop
Which port must be open between nodes for containers on different nodes to talk over an overlay network?
- 2377/tcp
- 4789/udp
- 443/tcp
- 2375/tcp