TExcelTAD
Home › Docker Swarm › Placement Constraints

Placement Constraints

By default, the scheduler may put a task on any active node. Real clusters are rarely that uniform: databases need the nodes with fast disks, GPU work needs the GPU nodes, ARM images need ARM nodes, and replicas should be spread over data centres or availability zones. Swarm offers three tools: constraints (hard rules), placement preferences (spread over groups) and max replicas per node (a cap).

Constraints: hard filters

A constraint is an expression attribute == value or attribute != value. A node must satisfy all constraints of a service to receive its tasks:

bash
$ docker service create --name db \
    --constraint node.labels.disk==ssd \
    --constraint node.role==worker \
    postgres:17
Attribute Example Notes
node.id node.id==k3x9v2m1q8w7 pin to one node (rarely a good idea)
node.hostname node.hostname!=worker-3 keep away from a node
node.role node.role==worker manager or worker; the classic "keep apps off managers"
node.platform.os node.platform.os==linux linux, windows
node.platform.arch node.platform.arch==aarch64 as reported by the engine: x86_64, aarch64
node.labels.<key> node.labels.zone==eu-1a labels set by managers with docker node update --label-add
engine.labels.<key> engine.labels.gpu==true labels from the node's own daemon.json

Node labels are covered in Managing Nodes; they are the main tool. There is no "or" and no "in": to allow two zones, label the eligible nodes with a common label (for example tier=web) and constrain on that.

If no node satisfies the constraints, the task does not fail; it stays pending with an explanation, and is placed as soon as a suitable node appears:

bash
$ docker service ps --no-trunc db
ID             NAME   IMAGE       NODE   DESIRED STATE   CURRENT STATE           ERROR
r5t6y7u8i9o0   db.1   postgres:17          Running         Pending 2 minutes ago   "no suitable node (scheduling constraints not satisfied on 5 nodes)"

(sample output)

Placement preferences: spread over groups

A placement preference says "spread the tasks evenly over the values of this label". With spread: node.labels.zone and nodes in three zones, six replicas become two per zone, regardless of how many nodes each zone has. That is what you want for availability: losing a zone loses a third of the replicas, not "whatever happened to land there".

Preferences are soft: they never make a task pending. Nodes without the label form one extra group of their own. You can list several preferences; they apply in order (for example zone first, then rack within the zone).

Max replicas per node

max_replicas_per_node caps how many tasks of the service one node may run. It is a hard rule like a constraint; tasks that do not fit stay pending (Scaling Services has a model of it).

The scheduler, step by step

Putting everything together, the scheduler handles each task like this:

  1. Filter the nodes: ready and active, satisfies every constraint, has the platform the image supports, has enough unreserved CPU and memory (Reservations & Limits), is below max_replicas_per_node, has the required plugins and free host ports (for mode: host publishing).
  2. Group the remaining nodes by the placement preferences and pick the group with the fewest tasks of this service.
  3. Spread inside the group: the node with the fewest tasks of this service, then the fewest tasks overall.

The model implements these three steps on a five-node cluster in which one node has no zone label:

python · try it yourself
nodes = {
    "w1": {"role": "worker", "labels": {"zone": "a", "disk": "ssd"}},
    "w2": {"role": "worker", "labels": {"zone": "a", "disk": "hdd"}},
    "w3": {"role": "worker", "labels": {"zone": "a", "disk": "ssd"}},
    "w4": {"role": "worker", "labels": {"zone": "b", "disk": "ssd"}},
    "w5": {"role": "worker", "labels": {"disk": "ssd"}},                # no zone label
    "m1": {"role": "manager", "labels": {"zone": "b"}},
}

def attr(node, key):
    n = nodes[node]
    if key == "node.role":
        return n["role"]
    if key == "node.hostname":
        return node
    if key.startswith("node.labels."):
        return n["labels"].get(key[len("node.labels."):])

def satisfies(node, constraint):
    op = "!=" if "!=" in constraint else "=="
    key, value = [p.strip() for p in constraint.split(op)]
    return (attr(node, key) == value) == (op == "==")

def schedule(service, replicas, constraints=(), spread=None, max_per_node=0):
    placed = []
    for slot in range(1, replicas + 1):
        ok = [n for n in nodes if all(satisfies(n, c) for c in constraints)
              and (not max_per_node or placed.count(n) < max_per_node)]
        if not ok:
            print(f"  {service}.{slot}: pending, no suitable node")
            continue
        if spread:
            groups = {}
            for n in ok:
                groups.setdefault(attr(n, spread) or "(no label)", []).append(n)
            per_group = {g: sum(placed.count(n) for n in ns) for g, ns in groups.items()}
            group = min(groups, key=lambda g: (per_group[g], g))
            ok = groups[group]
        node = min(ok, key=lambda n: (placed.count(n), n))
        placed.append(node)
    layout = {n: placed.count(n) for n in nodes if placed.count(n)}
    print(f"  {service}: {layout}")

print("web: 6 replicas, workers only")
schedule("web", 6, constraints=["node.role == worker"])
print("web: 6 replicas, workers only, spread over node.labels.zone")
schedule("web", 6, constraints=["node.role == worker"], spread="node.labels.zone")
print("db: 3 replicas, ssd workers, at most 1 per node")
schedule("db", 3, constraints=["node.role == worker", "node.labels.disk == ssd"], max_per_node=1)
print("cache: 2 replicas, zone b workers, at most 1 per node")
schedule("cache", 2, constraints=["node.role == worker", "node.labels.zone == b"], max_per_node=1)
web: 6 replicas, workers only
  web: {'w1': 2, 'w2': 1, 'w3': 1, 'w4': 1, 'w5': 1}
web: 6 replicas, workers only, spread over node.labels.zone
  web: {'w1': 1, 'w2': 1, 'w4': 2, 'w5': 2}
db: 3 replicas, ssd workers, at most 1 per node
  db: {'w1': 1, 'w3': 1, 'w4': 1}
cache: 2 replicas, zone b workers, at most 1 per node
  cache.2: pending, no suitable node
  cache: {'w4': 1}

Read the second result carefully: zone a has three nodes and zone b one, yet each group gets two tasks, and the unlabelled w5 counts as a third group. That is exactly how spread preferences behave, and why every node should carry the label you spread on. The last service shows a constraint that only one node satisfies: with a cap of one per node, the second replica waits.

In a stack file

compose · try it yourself
# $ docker stack config -c stack.yaml
# --- stack.yaml
services:
  web:
    image: nginx:1.27-alpine
    deploy:
      replicas: 6
      placement:
        constraints:
          - node.role == worker
        preferences:
          - spread: node.labels.zone
  db:
    image: postgres:17
    deploy:
      placement:
        constraints:
          - node.role == worker
          - node.labels.disk == ssd
        max_replicas_per_node: 1
version: "3.13"
services:
  db:
    deploy:
      placement:
        constraints:
          - node.role == worker
          - node.labels.disk == ssd
        max_replicas_per_node: 1
    image: postgres:17
  web:
    deploy:
      replicas: 6
      placement:
        constraints:
          - node.role == worker
        preferences:
          - spread: node.labels.zone
    image: nginx:1.27-alpine

docker stack config does not parse the constraint expressions; they are strings to it. A typo such as node.labels.zone = a (single =) passes config and is rejected only when the service is created, with an error saying the constraint needs an == or != operator. A typo in a label name (node.label.zone) or value is worse: it is valid syntax that matches no node, so the tasks stay pending. Check new constraints with docker service ps --no-trunc right after deploying.

Changing placement

bash
$ docker service update --constraint-add node.labels.zone==a web
$ docker service update --constraint-rm node.role==worker web
$ docker service update --placement-pref-add spread=node.labels.zone web
$ docker service update --replicas-max-per-node 2 web

Placement changes are service updates: tasks that no longer satisfy the new rules are replaced by a rolling update (Rolling Updates). In a stack, edit the file and redeploy.

Patterns

Goal Rule
keep applications off managers node.role == worker (or drain the managers)
stateful service with a local volume constraint to the node(s) holding the data: node.labels.pgdata == true (Volumes in a Swarm)
replicas across zones spread: node.labels.zone + max_replicas_per_node
mixed-architecture cluster node.platform.arch == aarch64 for ARM-only images (multi-arch images need no rule)
a node for noisy batch jobs label it pool=batch; batch services == batch, others != batch

Kubernetes expresses the same ideas with node selectors, affinity, taints and topology spread constraints, as described in Kubernetes scheduling. Swarm's version is simpler: no weights, no "prefer this node", no taints; a node accepts everything unless the services themselves stay away.

Learn more: Reservations & Limits · Managing Nodes · High Availability

Test yourself

A service has the constraint node.labels.disk==nvme, but no node has that label. What happens to its tasks?

  1. They run on any node
  2. They fail and the service is removed
  3. They stay pending with 'no suitable node' until a matching node appears
  4. docker stack config reports an error

Six replicas use spread: node.labels.zone. Zone a has 4 nodes, zone b has 2. How many replicas go to each zone?

  1. 4 and 2
  2. 3 and 3
  3. 6 and 0
  4. Random

How do you allow a service to run in zone a OR zone b?

  1. node.labels.zone==a|b
  2. Two constraints, one per zone
  3. Give the eligible nodes a shared label and constrain on it
  4. node.labels.zone in (a,b)