Replicated & Global Services
Every service has a mode that tells the orchestrator how many tasks it should have. Most services are replicated: "run N copies somewhere". Some must run on every node: log shippers, monitoring agents, node-level proxies. Those are global. Swarm also has two job modes for work that should finish rather than run forever.
The four modes
| Mode | CLI | Stack file | Number of tasks |
|---|---|---|---|
| replicated (default) | --replicas 3 |
mode: replicated, replicas: 3 |
exactly the number you ask for, spread over eligible nodes |
| global | --mode global |
mode: global |
one per eligible node; follows nodes joining and leaving |
| replicated job | --mode replicated-job --replicas 5 --max-concurrent 2 |
mode: replicated-job |
runs until the given number of tasks completed successfully |
| global job | --mode global-job |
mode: global-job |
one task per eligible node that runs to completion |
"Eligible" means: the node is Ready, its availability is active, and it satisfies the service's placement constraints (Placement Constraints). In docker service ls, a replicated service shows REPLICAS 3/3, a global one shows something like 5/5 that changes with the number of nodes, and jobs show completed counts such as 5/5 (2/5 completed) while running.
How the task count follows the cluster
The difference shows when nodes change. In the model, the cluster grows, a node is drained, and a GPU-only service is constrained to labelled nodes:
nodes = {"n1": {"avail": "active", "gpu": False},
"n2": {"avail": "active", "gpu": False},
"n3": {"avail": "active", "gpu": True}}
services = {
"api (replicated, 4)": {"mode": "replicated", "replicas": 4, "needs_gpu": False},
"node-exporter (global)": {"mode": "global", "needs_gpu": False},
"gpu-agent (global, gpu only)": {"mode": "global", "needs_gpu": True},
}
def eligible(svc):
return [n for n, s in nodes.items() if s["avail"] == "active" and (s["gpu"] or not svc["needs_gpu"])]
placed = {} # replicated service -> list of nodes, one entry per task
def task_counts(event):
print(event)
for name, svc in services.items():
el = eligible(svc)
if svc["mode"] == "global":
layout = {n: 1 for n in el}
else:
# keep tasks where they are; replace only those on nodes that are no longer eligible
tasks = [n for n in placed.get(name, []) if n in el]
while len(tasks) < svc["replicas"]:
tasks.append(min(el, key=lambda n: (tasks.count(n), n)))
placed[name] = tasks
layout = {n: tasks.count(n) for n in el if n in tasks}
total = sum(layout.values())
print(f" {name:<30} {total} task(s) {layout}")
task_counts("3 nodes:")
nodes["n4"] = {"avail": "active", "gpu": True}
task_counts("n4 joins (has a GPU):")
nodes["n1"]["avail"] = "drain"
task_counts("n1 drained:")3 nodes:
api (replicated, 4) 4 task(s) {'n1': 2, 'n2': 1, 'n3': 1}
node-exporter (global) 3 task(s) {'n1': 1, 'n2': 1, 'n3': 1}
gpu-agent (global, gpu only) 1 task(s) {'n3': 1}
n4 joins (has a GPU):
api (replicated, 4) 4 task(s) {'n1': 2, 'n2': 1, 'n3': 1}
node-exporter (global) 4 task(s) {'n1': 1, 'n2': 1, 'n3': 1, 'n4': 1}
gpu-agent (global, gpu only) 2 task(s) {'n3': 1, 'n4': 1}
n1 drained:
api (replicated, 4) 4 task(s) {'n2': 2, 'n3': 1, 'n4': 1}
node-exporter (global) 3 task(s) {'n2': 1, 'n3': 1, 'n4': 1}
gpu-agent (global, gpu only) 2 task(s) {'n3': 1, 'n4': 1}
The replicated service stays at four tasks whatever happens; only their location changes. The global services grow and shrink with the set of eligible nodes, and nobody has to scale them.
Note: n4 got no
apitask when it joined: existing replicas are never moved to a new node (see Managing Nodes). Only the two tasks from the drained n1 needed a new home, and the scheduler chose the least busy nodes. Global services, by contrast, start a task on a new node immediately.
Global services in a stack file
# $ docker stack config -c stack.yaml
# --- stack.yaml
services:
api:
image: ghcr.io/acme/shop-api:2.4.1
deploy:
replicas: 4
node-exporter:
image: prom/node-exporter:v1.9.1
deploy:
mode: global
resources:
limits:
memory: 64M
migrate:
image: ghcr.io/acme/shop-api:2.4.1
command: ["python", "manage.py", "migrate"]
deploy:
mode: replicated-job
replicas: 1version: "3.13"
services:
api:
deploy:
replicas: 4
image: ghcr.io/acme/shop-api:2.4.1
migrate:
command:
- python
- manage.py
- migrate
deploy:
mode: replicated-job
replicas: 1
image: ghcr.io/acme/shop-api:2.4.1
node-exporter:
deploy:
mode: global
resources:
limits:
memory: "67108864"
image: prom/node-exporter:v1.9.1
Typical global workloads: metrics agents (node-exporter, cAdvisor), log shippers, a reverse proxy published in host mode on every node, security scanners. Kubernetes calls the same idea a DaemonSet.
One docker stack config quirk worth knowing: it only checks the file against the Compose schema, not the Swarm rules. A global service with a replica count passes:
# $ docker stack config -c stack.yaml
# --- stack.yaml
services:
agent:
image: prom/node-exporter:v1.9.1
deploy:
mode: global
replicas: 2version: "3.13"
services:
agent:
deploy:
mode: global
replicas: 2
image: prom/node-exporter:v1.9.1
docker stack deploy rejects this file when it converts it into services: a replica count only makes sense for replicated services. A misspelled mode such as globel also passes config and fails at deploy time. Whatever is not a schema error only shows up when the stack is deployed.
Jobs
Job modes are for one-off or batch work: database migrations, a data import, a cleanup on every node. Their tasks are expected to complete (exit 0) and are not restarted after success. Failed tasks are retried according to the restart policy.
$ docker service create --name thumbnails --mode replicated-job \
--replicas 6 --max-concurrent 2 ghcr.io/acme/thumbnailer:1.3
$ docker service ls
ID NAME MODE REPLICAS IMAGE
c4d5e6f7g8h9 thumbnails replicated job 2/6 (2/6 completed) ghcr.io/acme/thumbnailer:1.3(sample output)
For a replicated job, --replicas is the number of successful completions wanted and --max-concurrent caps how many run at once (by default as many as --replicas). A model of the progress:
def run_job(total, max_concurrent, durations):
done, running, queue, t = 0, {}, list(range(1, total + 1)), 0
while done < total:
while queue and len(running) < max_concurrent:
i = queue.pop(0)
running[i] = t + durations[(i - 1) % len(durations)]
print(f"t={t:>2}s start task {i}")
t = min(running.values())
for i in sorted(running):
if running[i] == t:
del running[i]
done += 1
print(f"t={t:>2}s task {i} complete ({done}/{total} completed)")
print(f"job finished at t={t}s")
run_job(total=6, max_concurrent=2, durations=[10, 4, 7])t= 0s start task 1
t= 0s start task 2
t= 4s task 2 complete (1/6 completed)
t= 4s start task 3
t=10s task 1 complete (2/6 completed)
t=10s start task 4
t=11s task 3 complete (3/6 completed)
t=11s start task 5
t=15s task 5 complete (4/6 completed)
t=15s start task 6
t=20s task 4 complete (5/6 completed)
t=22s task 6 complete (6/6 completed)
job finished at t=22s
A job service stays in docker service ls after it completes. Changing its spec with docker service update (or adding --force) runs it again; there is no rolling update for jobs. Remove it with docker service rm when you no longer need its history. For scheduled jobs, Swarm has no cron: people use an external scheduler or a small cron-like container that calls the Docker API.
Choosing a mode
| You want… | Use |
|---|---|
| a stateless web app or API with N copies | replicated |
| exactly one copy of something (a singleton worker) | replicated with replicas: 1 |
| something on every node (agents, node-level ingress) | global |
| something on a subset of nodes, one each | global + a placement constraint |
| a migration before deploying the app | replicated job with 1 replica |
| a task once on every node | global job |
Learn more: Scaling Services · Placement Constraints · Kubernetes Jobs
Test yourself
A global service runs on 5 nodes. A sixth node joins the swarm. What happens?
- Nothing until you scale the service
- A task of the global service starts on the new node automatically
- One of the existing tasks moves to the new node
- The service becomes replicated
A stack file has mode: global and replicas: 2. What happens?
- docker stack config rejects it with a schema error
- docker stack config prints it unchanged, but docker stack deploy rejects it
- Swarm runs 2 tasks per node
- Replicas is silently ignored at deploy
Which mode fits a database migration that must run once and finish?
- global
- replicated with replicas: 0
- replicated-job with 1 replica
- global-job