Reservations & Limits
A cluster is a shared pool of CPU and memory. Without any resource settings, the scheduler treats every task as weightless: it will happily put ten memory-hungry replicas on one small node, and a single leaky container can push its neighbours into the kernel's out-of-memory killer. Swarm gives each service two separate controls: reservations for scheduling and limits for enforcement.
Two different questions
| Reservation | Limit | |
|---|---|---|
| Question it answers | "how much does a task need to be placed?" | "how much may a task use at most?" |
| Who uses it | the scheduler, when picking a node | the kernel (cgroups), while the container runs |
| CLI | --reserve-cpu 0.25 --reserve-memory 128M |
--limit-cpu 0.5 --limit-memory 256M --limit-pids 200 |
| Stack file | deploy.resources.reservations |
deploy.resources.limits |
| When exceeded | the task is not placed: pending "insufficient resources" | CPU: throttled. Memory: the container is OOM-killed (exit 137). PIDs: new processes fail |
| Kubernetes name | requests | limits |
The scheduler subtracts the reservations of every task on a node from the node's capacity (all of its CPUs and memory, as shown by docker node inspect) and only places a task where the rest still fits. Limits are not considered when scheduling, so limits can add up to more than a node has: that is overcommitment, and it is fine as long as tasks don't all hit their limits at once.
# $ docker stack config -c stack.yaml
# --- stack.yaml
services:
api:
image: ghcr.io/acme/shop-api:2.5.0
deploy:
replicas: 4
resources:
reservations:
cpus: "0.25"
memory: 256M
limits:
cpus: "1"
memory: 512M
pids: 200version: "3.13"
services:
api:
deploy:
replicas: 4
resources:
limits:
cpus: "1"
memory: "536870912"
pids: 200
reservations:
cpus: "0.25"
memory: "268435456"
image: ghcr.io/acme/shop-api:2.5.0
Where tasks fit
The model schedules services with reservations onto three nodes. Watch the last one:
nodes = {"worker-1": {"cpu": 2.0, "mem": 4096},
"worker-2": {"cpu": 2.0, "mem": 4096},
"worker-3": {"cpu": 4.0, "mem": 2048}}
used = {n: {"cpu": 0.0, "mem": 0, "tasks": 0} for n in nodes}
def place(task, cpu, mem):
fits = [n for n in nodes
if nodes[n]["cpu"] - used[n]["cpu"] >= cpu and nodes[n]["mem"] - used[n]["mem"] >= mem]
if not fits:
print(f"{task:<8} pending: no suitable node (insufficient resources on {len(nodes)} nodes)")
return
best = min(fits, key=lambda n: (used[n]["tasks"], n))
used[best]["cpu"] += cpu
used[best]["mem"] += mem
used[best]["tasks"] += 1
print(f"{task:<8} -> {best}")
for i in range(1, 5):
place(f"api.{i}", 0.5, 1024)
place("db.1", 1.0, 2048)
place("search.1", 2.0, 2048)
for n in nodes:
free_cpu = nodes[n]["cpu"] - used[n]["cpu"]
free_mem = nodes[n]["mem"] - used[n]["mem"]
print(f"{n}: free {free_cpu:g} CPU, {free_mem} MiB")api.1 -> worker-1
api.2 -> worker-2
api.3 -> worker-3
api.4 -> worker-1
db.1 -> worker-2
search.1 pending: no suitable node (insufficient resources on 3 nodes)
worker-1: free 1 CPU, 2048 MiB
worker-2: free 0.5 CPU, 1024 MiB
worker-3: free 3.5 CPU, 1024 MiB
search.1 needs 2 CPUs and 2 GiB. The cluster as a whole has more than that free, but no single node has both: worker-3 has the CPUs but not the memory, worker-1 has the memory but not the CPUs, and worker-2 has neither. The task waits until something changes. This is the most common reason for PENDING tasks after constraints, and the fix is either smaller reservations, bigger nodes, or moving something else.
Reservations are a promise, not a fence
A reservation does not stop a container from using more. A task that reserves 256M and actually uses 1G simply uses 1G. That is why you set both:
- the reservation at what the task typically needs, so the scheduler does not pack nodes too tightly;
- the limit at what it may reach in a bad moment, so that one container cannot take a node down.
Without reservations, the scheduler can only balance task counts. Without limits, a memory leak in one service becomes an outage for everything on the node.
What a limit does at runtime
CPU limits throttle: a container limited to 0.5 CPU gets at most half a CPU's worth of time in each scheduling period and becomes slower, never killed. Memory limits are final: when the container's memory reaches the limit and the kernel cannot reclaim enough, the OOM killer ends a process, the container exits with code 137 and the task becomes FAILED. Its replacement starts according to the restart policy:
limit_mb = 512
usage = 180 # MiB after start-up
leak_per_min = 45 # a slow memory leak
for minute in range(0, 12):
if usage >= limit_mb:
print(f"min {minute:>2}: {usage} MiB >= limit -> OOM kill, exit 137, task FAILED; new task starts at 180 MiB")
usage = 180
continue
bar = "#" * (usage // 32)
print(f"min {minute:>2}: {usage:>3} MiB {bar}")
usage += leak_per_minmin 0: 180 MiB #####
min 1: 225 MiB #######
min 2: 270 MiB ########
min 3: 315 MiB #########
min 4: 360 MiB ###########
min 5: 405 MiB ############
min 6: 450 MiB ##############
min 7: 495 MiB ###############
min 8: 540 MiB >= limit -> OOM kill, exit 137, task FAILED; new task starts at 180 MiB
min 9: 180 MiB #####
min 10: 225 MiB #######
min 11: 270 MiB ########
With a limit, the leak costs one container a restart every few minutes, which shows up clearly in docker service ps as a column of non-zero exit (137) errors. Without a limit, the leak grows until the whole node is short of memory, and the kernel may kill something else entirely, maybe the Docker daemon.
Choosing values
- Measure:
docker statson a node shows each container's CPU and memory use (see Resource Limits for single-host details). - Reservation ≈ normal usage (for example the median), limit ≈ peak plus a margin.
- Keep some capacity unreserved on every node for the engine, the OS and system services, and enough spare across the cluster to absorb a failed or drained node.
- Revisit after real traffic.
Generic resources (GPUs and others)
Besides CPU and memory, nodes can advertise generic resources, such as GPUs, in their daemon.json ("node-generic-resources": ["NVIDIA-GPU=GPU-7a1b..."]). Services reserve them like this:
# $ docker stack config -c stack.yaml
# --- stack.yaml
services:
trainer:
image: ghcr.io/acme/trainer:1.0
deploy:
resources:
reservations:
generic_resources:
- discrete_resource_spec:
kind: NVIDIA-GPU
value: 1version: "3.13"
services:
trainer:
deploy:
resources:
reservations:
generic_resources:
- discrete_resource_spec:
kind: NVIDIA-GPU
value: 1
image: ghcr.io/acme/trainer:1.0
The scheduler then only uses nodes with a free resource of that kind. Making the GPU actually usable inside the container still needs the NVIDIA runtime configured on the node.
Stack-file pitfalls
docker stack config is stricter than docker compose config in one place you will hit early: cpus must be a quoted string.
# $ docker stack config -c stack.yaml
# --- stack.yaml
services:
api:
image: ghcr.io/acme/shop-api:2.5.0
deploy:
resources:
limits:
cpus: 0.5services.api.deploy.resources.limits.cpus: must be a string
The service-level shortcuts of single-host Compose (mem_limit, cpus, pids_limit outside deploy) are not part of the stack format either; use deploy.resources. On the other hand, config does not compare values: a reservation larger than the limit passes it, and the problem only shows when the engine refuses to create such a container. Keep reservations below limits.
Learn more: Placement Constraints · Kubernetes resources · Compose production settings
Test yourself
Which setting does the Swarm scheduler use to decide whether a task fits on a node?
- limits
- reservations
- both, added together
- neither, only replica counts
A container with limits.memory: 512M grows past 512 MiB. What happens?
- It is throttled
- It is OOM-killed (exit 137) and the task is replaced according to the restart policy
- The node gives it more memory
- The service scales down
docker stack config fails with services.api.deploy.resources.limits.cpus: must be a string. What is the fix?
- Use
cpus: 1/2 - Quote the value:
cpus: "0.5" - Move
cpusto the service level - Use millicores:
cpus: 500m