Scaling Services
Scaling a replicated service means changing one number: the desired replica count. The orchestrator then creates or removes tasks until reality matches, and the scheduler decides where new tasks go. This lesson covers the commands, what happens on scale-up and scale-down, the per-node cap that can leave tasks pending, and how scaling fits with stack files.
The commands
$ docker service scale api=6
api scaled to 6
overall progress: 6 out of 6 tasks
1/6: running [==================================================>]
...
verify: Service api converged
$ docker service scale api=8 worker=3 # several services at once
$ docker service update --replicas 4 api # the same thing via update
$ docker service scale api=0 # stop all tasks, keep the service(sample output)
docker service scale is shorthand for docker service update --replicas. Scaling to 0 is a handy way to "switch off" a service without losing its definition, its published port or its configuration.
Only replicated services (and replicated jobs) have a replica count. Trying it on a global service fails:
$ docker service scale node-exporter=3
node-exporter: scale can only be used with replicated or replicated-job modeScaling up: where do new tasks go?
New tasks are placed one by one. For each task, the scheduler keeps the nodes that satisfy the constraints and have enough unreserved resources, then prefers the node that runs the fewest tasks of this service, and among those, the node with the fewest tasks overall. The result is an even spread that also takes other services into account:
# tasks already on each node: api replicas + other services
nodes = {
"worker-1": {"api": 2, "other": 3},
"worker-2": {"api": 1, "other": 0},
"worker-3": {"api": 1, "other": 4},
"worker-4": {"api": 0, "other": 5},
}
def place(service):
best = min(nodes, key=lambda n: (nodes[n][service], nodes[n][service] + nodes[n]["other"], n))
nodes[best][service] += 1
return best
print("scale api 4 -> 9")
for slot in range(5, 10):
node = place("api")
print(f" api.{slot} -> {node:<9} api per node: {[nodes[n]['api'] for n in nodes]}")scale api 4 -> 9
api.5 -> worker-4 api per node: [2, 1, 1, 1]
api.6 -> worker-2 api per node: [2, 2, 1, 1]
api.7 -> worker-3 api per node: [2, 2, 2, 1]
api.8 -> worker-4 api per node: [2, 2, 2, 2]
api.9 -> worker-2 api per node: [2, 3, 2, 2]
worker-4 is busy with other work, but it runs no api replica yet, so it gets the first new one: spreading replicas of the same service over nodes matters more for availability than balancing total load. Among the nodes with one api replica, the less busy worker-2 comes before worker-3.
Scaling down: which tasks go?
When the count drops, the orchestrator removes tasks that are not running first (pending or failed ones), then takes tasks from the nodes that run the most replicas of the service, so the remaining tasks stay spread out. The model removes four of nine:
tasks = {"api.1": "worker-1", "api.2": "worker-1", "api.3": "worker-2", "api.4": "worker-3",
"api.5": "worker-4", "api.6": "worker-2", "api.7": "worker-3", "api.8": "worker-1",
"api.9": "worker-4"}
state = {t: "running" for t in tasks}
state["api.7"] = "pending" # waiting for an image pull
def scale_down(to):
while len(tasks) > to:
per_node = {}
for t, n in tasks.items():
per_node[n] = per_node.get(n, 0) + 1
victim = max(tasks, key=lambda t: (state[t] != "running", per_node[tasks[t]], int(t.split(".")[1])))
print(f" remove {victim:<6} from {tasks[victim]} ({state[victim]})")
del tasks[victim]
print("scale api 9 -> 5")
scale_down(5)
print("left:", {n: sorted(t for t in tasks if tasks[t] == n) for n in sorted(set(tasks.values()))})scale api 9 -> 5
remove api.7 from worker-3 (pending)
remove api.8 from worker-1 (running)
remove api.9 from worker-4 (running)
remove api.6 from worker-2 (running)
left: {'worker-1': ['api.1', 'api.2'], 'worker-2': ['api.3'], 'worker-3': ['api.4'], 'worker-4': ['api.5']}
The pending task went first (removing it costs nothing), then one from worker-1, the only node with three replicas, then one each from worker-4 and worker-2, which had two. Every node still runs at least one replica afterwards. (Ties are broken by the highest slot number in this model; the real orchestrator's tie-breaking is an internal detail.)
The per-node cap: max_replicas_per_node
Sometimes you want no more than N replicas on any one node, for example to keep a node failure from taking out too much capacity, or because the app binds a host port. deploy.placement.max_replicas_per_node (CLI: --replicas-max-per-node) enforces it. If you ask for more replicas than nodes × cap, the extra tasks stay pending:
nodes = ["worker-1", "worker-2", "worker-3"]
cap = 2
def scale(replicas):
load = {n: 0 for n in nodes}
pending = 0
for _ in range(replicas):
room = [n for n in nodes if load[n] < cap]
if not room:
pending += 1
continue
load[min(room, key=lambda n: (load[n], n))] += 1
note = f", {pending} pending: no suitable node (max replicas per node limit exceed)" if pending else ""
print(f"replicas={replicas}: running {replicas - pending}{note} {load}")
for r in (4, 6, 8):
scale(r)
nodes.append("worker-4")
print("worker-4 joins:")
scale(8)replicas=4: running 4 {'worker-1': 2, 'worker-2': 1, 'worker-3': 1}
replicas=6: running 6 {'worker-1': 2, 'worker-2': 2, 'worker-3': 2}
replicas=8: running 6, 2 pending: no suitable node (max replicas per node limit exceed) {'worker-1': 2, 'worker-2': 2, 'worker-3': 2}
worker-4 joins:
replicas=8: running 8 {'worker-1': 2, 'worker-2': 2, 'worker-3': 2, 'worker-4': 2}
The pending tasks are not an error you have to fix by hand: as soon as a node with room appears, the scheduler places them. In docker service ps, such tasks show the reason in the ERROR column, which is the first thing to check when REPLICAS stays at 6/8.
In a stack file, both settings sit under deploy:
# $ docker stack config -c stack.yaml
# --- stack.yaml
services:
api:
image: ghcr.io/acme/shop-api:2.4.1
deploy:
replicas: ${API_REPLICAS:-3}
placement:
max_replicas_per_node: 2version: "3.13"
services:
api:
deploy:
replicas: 3
placement:
max_replicas_per_node: 2
image: ghcr.io/acme/shop-api:2.4.1
The replica count can come from a variable with a default, which is convenient for using one stack file in several environments. A wrong value is caught early:
# $ docker stack config -c stack.yaml
# --- stack.yaml
services:
api:
image: ghcr.io/acme/shop-api:2.4.1
deploy:
replicas: ${API_REPLICAS:-three}error while interpolating services.api.deploy.replicas: failed to cast to expected type: strconv.Atoi: parsing "three": invalid syntax
Note: unlike
docker compose,docker stack configanddocker stack deploydo not read a.envfile. Variables must be exported in the shell that runs the command. Stack Variables & docker stack config covers the details.
Scaling and stack files
docker service scale changes the live service, not your stack file. The next docker stack deploy sets the replica count back to what the file says. For anything you want to keep, change the file (or the variable) and redeploy; use service scale for quick, temporary changes, such as absorbing a traffic spike while you prepare a proper change.
What Swarm does not do: autoscaling
Swarm has no built-in autoscaler. Replica counts change only when someone (or something) asks. Options:
- scale on a schedule from CI or cron (
docker service scale api=10before the morning peak); - a small controller that reads metrics (Prometheus, for example) and calls the Docker API;
- capacity planning: enough replicas for the peak plus a failed node.
Kubernetes ships a HorizontalPodAutoscaler for this; on Swarm you build or skip it. Compose can scale on a single host too (Compose scaling), but without spreading across machines.
Learn more: Placement Constraints · Reservations & Limits · Inspecting Services
Test yourself
You scale a service from 4 to 5 replicas. Which node does the new task prefer?
- The node with the most free disk
- A node that runs the fewest tasks of this service
- Always a manager
- The node where the last task started
A service has max_replicas_per_node: 2, 3 eligible nodes and replicas: 8. What happens?
- 8 tasks run, the cap is a hint
- 6 run and 2 stay pending until a node with room appears
- The deploy fails
- The cap is raised to 3 automatically
You ran docker service scale shop_api=10 on a stack service whose file says replicas: 4. What happens on the next docker stack deploy?
- The service keeps 10 replicas
- It goes back to 4, because the stack file is the desired state
- Deploy fails
- It becomes 14