Troubleshooting
Most Swarm problems fall into a handful of patterns: a stack file that doesn't deploy, tasks stuck in Pending, tasks that start and die in a loop, and services that run but can't be reached. This lesson gives you a method for each, the commands that reveal the cause, and a decision tree you can run.
The four commands to start with
$ docker service ls # which service is short of replicas?
$ docker service ps --no-trunc shop_api # task history, with the full ERROR column
$ docker service inspect --pretty shop_api # the spec the swarm is trying to achieve
$ docker node ls # are all nodes Ready/Active?docker service ps is the most useful by far. It lists not only running tasks but the recent failed ones, each with a desired state, a current state and an error:
$ docker service ps --no-trunc --format 'table {{.Name}}\t{{.Node}}\t{{.CurrentState}}\t{{.Error}}' shop_api
NAME NODE CURRENT STATE ERROR
shop_api.1 worker-1 Running 2 minutes ago
shop_api.2 Pending 2 minutes ago no suitable node (insufficient resources on 3 nodes)
shop_api.3 worker-2 Failed 30 seconds ago task: non-zero exit (1)
\_ shop_api.3 worker-2 Failed 1 minute ago task: non-zero exit (1)
shop_api.4 worker-3 Rejected 10 seconds ago No such image: ghcr.io/acme/shop-api:2.4.l(sample output.) Each line points to a different problem class.
Task states in brief
NEW → PENDING → ASSIGNED → ACCEPTED → PREPARING → STARTING → RUNNING
│ │ │ │
no node fits image pull fails exits exits / unhealthy
(stays Pending) (Rejected) (Failed) (Failed / Shutdown)- Pending: the scheduler found no node for the task. The task waits; nothing is retried until something changes (a node joins, resources free up).
- Rejected: a node accepted the task but couldn't create the container (image pull, bad mount source, unknown network plugin).
- Failed: the container ran and exited with an error, or was killed for failing its healthcheck or for exceeding its memory limit (
exit (137)).
The pending-task decision tree
A task in Pending has an error message from the scheduler. This runnable tree walks through the usual causes in the order you should check them:
def diagnose(c):
if not c["nodes_ready"]:
return "no Ready+Active nodes: check `docker node ls` (Down? Drain? Pause?)"
if c["constraint_matches"] == 0:
return ("constraints match no node: compare `deploy.placement.constraints` with "
"`docker node inspect --format '{{json .Spec.Labels}}'` (typo in a label?)")
if c["fits_resources"] == 0:
return ("insufficient resources: reservations exceed free CPU/memory on every matching node; "
"lower reservations, add nodes, or free capacity")
if c["max_per_node_reached"]:
return "max_replicas_per_node reached on every matching node: add nodes or raise the limit"
if c["host_port_taken"]:
return "a `mode: host` port is already used on every candidate node"
if c["platform_mismatch"]:
return "image platform (e.g. arm64 only) matches no node's architecture"
return "should schedule: check `docker service ps` again, or the managers' logs"
cases = {
"label typo": dict(nodes_ready=True, constraint_matches=0, fits_resources=0, max_per_node_reached=False, host_port_taken=False, platform_mismatch=False),
"too big": dict(nodes_ready=True, constraint_matches=3, fits_resources=0, max_per_node_reached=False, host_port_taken=False, platform_mismatch=False),
"host port": dict(nodes_ready=True, constraint_matches=2, fits_resources=2, max_per_node_reached=False, host_port_taken=True, platform_mismatch=False),
"all drained": dict(nodes_ready=False, constraint_matches=0, fits_resources=0, max_per_node_reached=False, host_port_taken=False, platform_mismatch=False),
"arm image": dict(nodes_ready=True, constraint_matches=3, fits_resources=3, max_per_node_reached=False, host_port_taken=False, platform_mismatch=True),
}
for name, c in cases.items():
print(f"{name:<12} -> {diagnose(c)}")label typo -> constraints match no node: compare `deploy.placement.constraints` with `docker node inspect --format '{{json .Spec.Labels}}'` (typo in a label?)
too big -> insufficient resources: reservations exceed free CPU/memory on every matching node; lower reservations, add nodes, or free capacity
host port -> a `mode: host` port is already used on every candidate node
all drained -> no Ready+Active nodes: check `docker node ls` (Down? Drain? Pause?)
arm image -> image platform (e.g. arm64 only) matches no node's architecture
The real error messages map onto these branches: no suitable node (scheduling constraints not satisfied on 3 nodes), no suitable node (insufficient resources on 3 nodes), no suitable node (max replicas per node limit exceed), host-mode port already in use on 2 nodes, unsupported platform on 3 nodes.
Crash loops
A task that keeps failing is replaced again and again (subject to restart_policy.delay and max_attempts). Find out why the container exits:
$ docker service ps --no-trunc shop_api | head -3 # exit code in ERROR
$ docker service logs --tail 50 shop_api # what the app printed
$ docker inspect --format '{{json .Status.ContainerStatus}}' <task-id>
{"ContainerID":"9c1f…","PID":0,"ExitCode":137}(sample output.) Common exit codes:
| Exit | Usual cause |
|---|---|
| 1 or 2 | the application failed: bad config, missing env var or secret file, can't reach a dependency at start-up |
| 126 / 127 | command not executable / not found (wrong command or entrypoint) |
| 137 | killed: out of memory (limit too low) or failed healthcheck |
| 139 | segmentation fault |
| 143 | stopped with SIGTERM (normal during updates) |
Remember that Swarm ignores depends_on: an app that exits when its database isn't ready yet will crash-loop until the database is up. Add retries in the app, or a start-up wait.
Problems before deploy
Catch file problems before they reach the cluster. docker stack config validates the schema and types:
# $ docker stack config -c stack.yaml
# --- stack.yaml
services:
api:
image: ghcr.io/acme/shop-api:2.4.1
deploy:
replicas: threeservices.api.deploy.replicas: must be an integer
But it does not check references between objects. A service that uses a network or secret the file never declares passes stack config and only fails at deploy time. docker compose config does check references, so running both in CI catches more:
# $ docker stack config -c stack.yaml
# $ docker compose -f stack.yaml config -q
# --- stack.yaml
services:
api:
image: ghcr.io/acme/shop-api:2.4.1
networks: [back]$ docker stack config -c stack.yaml
version: "3.13"
services:
api:
image: ghcr.io/acme/shop-api:2.4.1
networks:
back: null
$ docker compose -f stack.yaml config -q
service "api" refers to undefined network back: invalid compose project
The two checks complement each other: docker compose config follows the newer Compose Specification, so it happily accepts keys that the stack loader rejects (like profiles or a top-level name:). Neither one replaces the other.
Reachability problems
When tasks run but requests fail:
- Inside the overlay: does the name resolve?
docker exec <container> nslookup api(needs a tool in the image, or use an attachable network andnicolaka/netshoot). If it doesn't, the two services don't share a network. - Between nodes: if containers on the same node can talk but across nodes can't, it's the firewall (4789/udp, 7946) or MTU (Overlay Networks).
- From outside: does
curl http://<any-node>:<port>work on every node? If only nodes with tasks answer, the port is inmode: hostor the ingress network is broken (The Routing Mesh). - Healthchecks: an unhealthy task is removed from load balancing; check
docker inspect --format '{{json .State.Health}}' <container>on its node.
Node and manager trouble
| Symptom | Check |
|---|---|
node Down |
is Docker running on it? can it reach managers on 2377? clock skew (TLS fails with large time differences)? |
Error: This node is not a swarm manager |
you're on a worker: run the command on a manager, or use a Docker context pointing at one |
The swarm does not have a leader |
quorum lost: see Raft & Quorum and Backup & Restore |
Swarm is encrypted and needs to be unlocked |
autolock: docker swarm unlock (Swarm Security) |
| tasks unevenly spread after an outage | expected: docker service update --force <svc> to rebalance |
Learn more: Inspecting Services · Logging & Monitoring · Kubernetes troubleshooting
Test yourself
A task stays in Pending with no suitable node (insufficient resources on 4 nodes). What is the cause?
- The image doesn't exist
- The service's reservations don't fit the free CPU/memory of any eligible node
- The container exits with code 1
- The overlay network is down
A task's ERROR column shows No such image: ghcr.io/acme/shop-api:2.4.l. Which state is the task in?
- Pending
- Rejected
- Running
- Complete
A stack file refers to network back that it never declares. What does docker stack config do?
- Reports an undefined network
- Prints the file without complaint; the problem appears at deploy time
- Creates the network
- Removes the reference