Swarm Exercises
Time to practise. Exercises 1–7 model one Swarm mechanism each in Python: the starter playground runs as-is and prints placeholder results, so you can see the format. Replace the TODO parts, press ▶ Run, and compare your output with the "Expected" lines. Exercises 8–10 are stack files to fix: the starter shows what docker stack config says about the broken file. Solutions are hidden below each exercise; try for a few minutes first!
| # | Exercise | Concept |
|---|---|---|
| 1 | Quorum calculator | Raft & Quorum |
| 2 | Spread the replicas | Placement |
| 3 | Constraint matcher | Placement Constraints |
| 4 | Rolling update batches | Rolling Updates |
| 5 | Routing mesh round robin | The Routing Mesh |
| 6 | VIP or task IPs? | Service Discovery |
| 7 | Versioned config names | Configs |
| 8 | Make it stack-ready | Stack Files & deploy |
| 9 | Required variables | Stack Variables |
| 10 | Production override | Stack Files & deploy |
1. Quorum calculator
Write status(total, down) that returns "OK (tolerates N more)" when the swarm still has quorum, and "NO QUORUM" otherwise.
Expected:
3 managers, 1 down: OK (tolerates 0 more)
5 managers, 1 down: OK (tolerates 1 more)
5 managers, 3 down: NO QUORUM
4 managers, 2 down: NO QUORUMdef status(total, down):
# TODO: quorum = majority of ALL managers (down ones still count)
return "?"
for total, down in [(3, 1), (5, 1), (5, 3), (4, 2)]:
print(f"{total} managers, {down} down: {status(total, down)}")3 managers, 1 down: ?
5 managers, 1 down: ?
5 managers, 3 down: ?
4 managers, 2 down: ?
Show solution
def status(total, down):
quorum = total // 2 + 1
alive = total - down
if alive < quorum:
return "NO QUORUM"
return f"OK (tolerates {alive - quorum} more)"
for total, down in [(3, 1), (5, 1), (5, 3), (4, 2)]:
print(f"{total} managers, {down} down: {status(total, down)}")3 managers, 1 down: OK (tolerates 0 more)
5 managers, 1 down: OK (tolerates 1 more)
5 managers, 3 down: NO QUORUM
4 managers, 2 down: NO QUORUM
2. Spread the replicas
Place n replicas one at a time on the node that currently runs the fewest replicas of the service (ties: alphabetical node name). Return the count per node.
Expected:
{'node-a': 2, 'node-b': 2, 'node-c': 1}
{'node-a': 1, 'node-b': 1, 'node-c': 0}def spread(nodes, n):
counts = {node: 0 for node in nodes}
# TODO: place n replicas
return counts
print(spread(["node-b", "node-a", "node-c"], 5))
print(spread(["node-c", "node-b", "node-a"], 2)){'node-b': 0, 'node-a': 0, 'node-c': 0}
{'node-c': 0, 'node-b': 0, 'node-a': 0}
Show solution
def spread(nodes, n):
counts = {node: 0 for node in sorted(nodes)}
for _ in range(n):
target = min(counts, key=lambda node: (counts[node], node))
counts[target] += 1
return counts
print(spread(["node-b", "node-a", "node-c"], 5))
print(spread(["node-c", "node-b", "node-a"], 2)){'node-a': 2, 'node-b': 2, 'node-c': 1}
{'node-a': 1, 'node-b': 1, 'node-c': 0}
3. Constraint matcher
Write eligible(nodes, constraints) that returns the names of nodes matching every constraint. Constraints look like node.role == worker, node.labels.zone != a or node.hostname == n3.
Expected:
['n2', 'n4']
['n4']
[]nodes = [
{"hostname": "n1", "role": "manager", "labels": {"zone": "a"}},
{"hostname": "n2", "role": "worker", "labels": {"zone": "a", "ssd": "true"}},
{"hostname": "n3", "role": "worker", "labels": {"zone": "b"}},
{"hostname": "n4", "role": "worker", "labels": {"zone": "c", "ssd": "true"}},
]
def eligible(nodes, constraints):
# TODO: parse "left op right" and compare with the node's attribute or label
return [n["hostname"] for n in nodes]
print(eligible(nodes, ["node.role == worker", "node.labels.ssd == true"]))
print(eligible(nodes, ["node.labels.ssd == true", "node.labels.zone != a"]))
print(eligible(nodes, ["node.labels.gpu == true"]))['n1', 'n2', 'n3', 'n4']
['n1', 'n2', 'n3', 'n4']
['n1', 'n2', 'n3', 'n4']
Show solution
nodes = [
{"hostname": "n1", "role": "manager", "labels": {"zone": "a"}},
{"hostname": "n2", "role": "worker", "labels": {"zone": "a", "ssd": "true"}},
{"hostname": "n3", "role": "worker", "labels": {"zone": "b"}},
{"hostname": "n4", "role": "worker", "labels": {"zone": "c", "ssd": "true"}},
]
def value(node, key):
if key.startswith("node.labels."):
return node["labels"].get(key[len("node.labels."):])
return node.get(key[len("node."):])
def matches(node, constraint):
op = "==" if "==" in constraint else "!="
left, right = (part.strip() for part in constraint.split(op))
actual = value(node, left)
return actual == right if op == "==" else actual != right
def eligible(nodes, constraints):
return [n["hostname"] for n in nodes if all(matches(n, c) for c in constraints)]
print(eligible(nodes, ["node.role == worker", "node.labels.ssd == true"]))
print(eligible(nodes, ["node.labels.ssd == true", "node.labels.zone != a"]))
print(eligible(nodes, ["node.labels.gpu == true"]))['n2', 'n4']
['n4']
[]
4. Rolling update batches
With parallelism: p, Swarm updates tasks in batches of p (and parallelism: 0 means all at once). Return the batches of slot numbers for a service with replicas tasks.
Expected:
[[1, 2], [3, 4], [5]]
[[1], [2], [3]]
[[1, 2, 3, 4]]def batches(replicas, parallelism):
# TODO
return [list(range(1, replicas + 1))]
print(batches(5, 2))
print(batches(3, 1))
print(batches(4, 0))[[1, 2, 3, 4, 5]]
[[1, 2, 3]]
[[1, 2, 3, 4]]
Show solution
def batches(replicas, parallelism):
slots = list(range(1, replicas + 1))
size = parallelism or replicas
return [slots[i:i + size] for i in range(0, replicas, size)]
print(batches(5, 2))
print(batches(3, 1))
print(batches(4, 0))[[1, 2], [3, 4], [5]]
[[1], [2], [3]]
[[1, 2, 3, 4]]
5. Routing mesh round robin
Every node keeps its own round-robin pointer over the service's healthy tasks (sorted by name). Write route(entry_node) that returns the task chosen for a new connection.
Expected:
['web.1', 'web.2', 'web.3', 'web.1']
['web.1', 'web.3']healthy = {"web.1", "web.2", "web.3"}
pointers = {}
def route(entry_node):
# TODO: per-node pointer over sorted(healthy)
return "web.?"
print([route("node-1") for _ in range(4)])
healthy.discard("web.2")
print([route("node-2") for _ in range(2)])['web.?', 'web.?', 'web.?', 'web.?']
['web.?', 'web.?']
Show solution
healthy = {"web.1", "web.2", "web.3"}
pointers = {}
def route(entry_node):
backends = sorted(healthy)
i = pointers.get(entry_node, 0)
pointers[entry_node] = i + 1
return backends[i % len(backends)]
print([route("node-1") for _ in range(4)])
healthy.discard("web.2")
print([route("node-2") for _ in range(2)])['web.1', 'web.2', 'web.3', 'web.1']
['web.1', 'web.3']
6. VIP or task IPs?
Write lookup(name) for the embedded DNS: a vip service returns its VIP, a dnsrr service returns all its task IPs, tasks.<svc> always returns the task IPs, unknown names return None.
Expected:
api -> ['10.0.1.2']
tasks.api -> ['10.0.1.5', '10.0.1.6']
cache -> ['10.0.1.9', '10.0.1.10']
db -> Noneservices = {
"api": {"endpoint_mode": "vip", "vip": "10.0.1.2", "tasks": ["10.0.1.5", "10.0.1.6"]},
"cache": {"endpoint_mode": "dnsrr", "vip": None, "tasks": ["10.0.1.9", "10.0.1.10"]},
}
def lookup(name):
# TODO
return None
for q in ["api", "tasks.api", "cache", "db"]:
print(q, "->", lookup(q))api -> None
tasks.api -> None
cache -> None
db -> None
Show solution
services = {
"api": {"endpoint_mode": "vip", "vip": "10.0.1.2", "tasks": ["10.0.1.5", "10.0.1.6"]},
"cache": {"endpoint_mode": "dnsrr", "vip": None, "tasks": ["10.0.1.9", "10.0.1.10"]},
}
def lookup(name):
if name.startswith("tasks."):
svc = services.get(name[len("tasks."):])
return svc and svc["tasks"]
svc = services.get(name)
if svc is None:
return None
return [svc["vip"]] if svc["endpoint_mode"] == "vip" else svc["tasks"]
for q in ["api", "tasks.api", "cache", "db"]:
print(q, "->", lookup(q))api -> ['10.0.1.2']
tasks.api -> ['10.0.1.5', '10.0.1.6']
cache -> ['10.0.1.9', '10.0.1.10']
db -> None
7. Versioned config names
Given a list of deploys (each the content of nginx.conf), name each config nginx_<n> where n increases only when the content changed since the previous deploy, and say whether the service rolls.
Expected:
deploy 1: nginx_1 (rolling update)
deploy 2: nginx_1 (no change)
deploy 3: nginx_2 (rolling update)
deploy 4: nginx_3 (rolling update)deploys = ["workers 2", "workers 2", "workers 4", "workers 2"]
# TODO: track the previous content and the current revision
for i, content in enumerate(deploys, 1):
print(f"deploy {i}: nginx_? (?)")deploy 1: nginx_? (?)
deploy 2: nginx_? (?)
deploy 3: nginx_? (?)
deploy 4: nginx_? (?)
Show solution
deploys = ["workers 2", "workers 2", "workers 4", "workers 2"]
previous, revision = None, 0
for i, content in enumerate(deploys, 1):
changed = content != previous
if changed:
revision += 1
previous = content
print(f"deploy {i}: nginx_{revision} ({'rolling update' if changed else 'no change'})")deploy 1: nginx_1 (rolling update)
deploy 2: nginx_1 (no change)
deploy 3: nginx_2 (rolling update)
deploy 4: nginx_3 (rolling update)
Note that deploy 4 goes back to the content of deploy 1 but still gets a new name: an old config may already have been removed. A content hash as the name (see Configs) would reuse nginx_1 instead.
8. Make it stack-ready
This Compose file works with docker compose up but the stack loader rejects it. Fix it so that docker stack config prints it, keeping the intent: a 3-replica api that restarts on failure, and the debug tool only when needed (hint: a separate file). The loader stops at the first problem it finds, so expect to fix them one by one.
# $ docker stack config -c stack.yaml
# --- stack.yaml
name: shop
services:
api:
image: ghcr.io/acme/shop-api:2.4.1
restart: on-failure
depends_on:
db:
condition: service_healthy
deploy:
replicas: 3
db:
image: postgres:17
debug:
image: nicolaka/netshoot
profiles: [debug]services.api.depends_on: must be a list
Show solution
Remove name: (the stack name is the deploy argument), use deploy.restart_policy instead of restart, drop the long depends_on (Swarm ignores start order anyway; the app must retry), and move debug out into its own file deployed only when needed.
# $ docker stack config -c stack.yaml
# --- stack.yaml
services:
api:
image: ghcr.io/acme/shop-api:2.4.1
deploy:
replicas: 3
restart_policy:
condition: on-failure
db:
image: postgres:17version: "3.13"
services:
api:
deploy:
replicas: 3
restart_policy:
condition: on-failure
image: ghcr.io/acme/shop-api:2.4.1
db:
image: postgres:17
9. Required variables
The deploy below silently produced the image ghcr.io/acme/shop-api: and 1 replica. Change the file so that a missing TAG stops the deploy with a clear message, while REPLICAS defaults to 3.
# $ docker stack config -c stack.yaml
# --- stack.yaml
services:
api:
image: ghcr.io/acme/shop-api:${TAG}
deploy:
replicas: ${REPLICAS:-1}version: "3.13"
services:
api:
deploy:
replicas: 1
image: 'ghcr.io/acme/shop-api:'
Show solution
# $ docker stack config -c stack.yaml
# --- stack.yaml
services:
api:
image: ghcr.io/acme/shop-api:${TAG:?TAG must be set to a release tag}
deploy:
replicas: ${REPLICAS:-3}invalid interpolation format for services.api.image: "required variable TAG is missing a value: TAG must be set to a release tag"; you may need to escape any $ with another $
The playground runs with no variables set, so the error above is the result you want: the deploy stops before anything reaches the cluster. To check the rest of the file without setting TAG, use docker stack config --skip-interpolation.
10. Production override
base.yaml is shared by all environments. Write prod.yaml so that the merged result has 6 replicas, LOG_LEVEL: warn, a memory limit of 512M and only port 443 published (target 8443). Hint: list merges append, so move the port out of the base file.
# $ docker stack config -c base.yaml -c prod.yaml
# --- base.yaml
services:
web:
image: ghcr.io/acme/shop-web:3.2.0
ports: ["8080:8443"]
environment:
LOG_LEVEL: debug
deploy:
replicas: 1
# --- prod.yaml
services:
web:
ports: ["443:8443"]version: "3.13"
services:
web:
deploy:
replicas: 1
environment:
LOG_LEVEL: debug
image: ghcr.io/acme/shop-web:3.2.0
ports:
- mode: ingress
target: 8443
published: 443
protocol: tcp
- mode: ingress
target: 8443
published: 8080
protocol: tcp
Show solution
# $ docker stack config -c base.yaml -c prod.yaml
# --- base.yaml
services:
web:
image: ghcr.io/acme/shop-web:3.2.0
environment:
LOG_LEVEL: debug
deploy:
replicas: 1
# --- prod.yaml
services:
web:
ports: ["443:8443"]
environment:
LOG_LEVEL: warn
deploy:
replicas: 6
resources:
limits: {memory: 512M}version: "3.13"
services:
web:
deploy:
replicas: 6
resources:
limits:
memory: "536870912"
environment:
LOG_LEVEL: warn
image: ghcr.io/acme/shop-web:3.2.0
ports:
- mode: ingress
target: 8443
published: 443
protocol: tcp
A dev.yaml would then add "8080:8443" for local testing.
Test yourself
Which file layout lets you publish a different port per environment without ending up with both ports?
- Put the port in base.yaml and override it in prod.yaml
- Leave ports out of base.yaml and set them only in each environment file
- Use
!overridein prod.yaml - Use two
ports:keys in one file
In exercise 4, what does parallelism: 0 mean for a rolling update?
- No tasks are updated
- One task at a time
- All tasks at once
- It's invalid