Services & Tasks
On a single host you run containers. In a swarm you declare services, and the swarm runs containers for you. This lesson explains the three layers (service → task → container), how to create and list services, the lifecycle every task goes through, and the restart policy that decides what happens when a container exits.
Three layers
service "api" (desired state: image, replicas=3, ports, env, limits ...)
|
+-- task api.1 --> node worker-1 --> container api.1.x7k2...
+-- task api.2 --> node worker-2 --> container api.2.p9m4...
+-- task api.3 --> node worker-1 --> container api.3.c3v8...- A service is the specification. It lives in the managers' Raft store and never runs anything itself.
- A task is one unit of scheduled work: "a container for slot 2 of
api, on worker-2". Tasks are created by the orchestrator, placed by the scheduler and never move: if a task's container dies, the task ends and a new task takes over the same slot. - A container is what the node's Docker Engine starts for a task. Its name is
<service>.<slot>.<task-id>.
Thinking in slots helps: a 3-replica service has slots 1, 2 and 3. Each slot always has at most one task that is supposed to run, plus a short history of previous tasks.
Creating a service
docker service create takes most of the options of docker run, plus cluster options:
$ docker service create \
--name api \
--replicas 3 \
--publish published=8000,target=8000 \
--env LOG_LEVEL=info \
--limit-memory 256M \
--restart-condition on-failure \
ghcr.io/acme/shop-api:2.4.1
x1y2z3a4b5c6d7e8f9g0h1i2j
overall progress: 3 out of 3 tasks
1/3: running [==================================================>]
2/3: running [==================================================>]
3/3: running [==================================================>]
verify: Service x1y2z3a4b5c6d7e8f9g0h1i2j convergeddocker run |
docker service create |
Note |
|---|---|---|
--name |
--name |
the service name, also its DNS name on overlay networks |
-p 8000:8000 |
--publish 8000:8000 |
published on every node through the routing mesh |
-v vol:/data |
--mount type=volume,src=vol,dst=/data |
volumes are per node (Volumes in a Swarm) |
--restart |
--restart-condition, --restart-delay, --restart-max-attempts |
below |
--memory |
--limit-memory, --reserve-memory |
Reservations & Limits |
-d |
--detach |
by default the CLI waits for convergence and shows progress |
--replicas, --mode, --constraint, --update-* |
cluster-only |
In practice you will write services in stack files and deploy them with docker stack deploy (Stacks). The same service as a stack file, checked with docker stack config:
# $ docker stack config -c stack.yaml
# --- stack.yaml
services:
api:
image: ghcr.io/acme/shop-api:2.4.1
environment:
LOG_LEVEL: info
ports:
- "8000:8000"
deploy:
replicas: 3
resources:
limits:
memory: 256M
restart_policy:
condition: on-failureversion: "3.13"
services:
api:
deploy:
replicas: 3
resources:
limits:
memory: "268435456"
restart_policy:
condition: on-failure
environment:
LOG_LEVEL: info
image: ghcr.io/acme/shop-api:2.4.1
ports:
- mode: ingress
target: 8000
published: 8000
protocol: tcp
Notice that 256M came out as a number of bytes: the stack command converts sizes to what the Swarm API expects. Inside a stack, the service is named <stack>_api, for example shop_api.
Listing services and tasks
$ docker service ls
ID NAME MODE REPLICAS IMAGE PORTS
x1y2z3a4b5c6 api replicated 3/3 ghcr.io/acme/shop-api:2.4.1 *:8000->8000/tcp
$ docker service ps api
ID NAME IMAGE NODE DESIRED STATE CURRENT STATE ERROR PORTS
q8w7e6r5t4y3 api.1 ghcr.io/acme/shop-api:2.4.1 worker-1 Running Running 2 minutes ago
m1n2b3v4c5x6 api.2 ghcr.io/acme/shop-api:2.4.1 worker-2 Running Running 40 seconds ago
z0a9s8d7f6g5 \_ api.2 ghcr.io/acme/shop-api:2.4.1 worker-2 Shutdown Failed 45 seconds ago "task: non-zero exit (137)"
p0o9i8u7y6t5 api.3 ghcr.io/acme/shop-api:2.4.1 worker-1 Running Running 2 minutes ago(sample output)
REPLICAS 3/3 means three running out of three desired. In service ps, the line starting with \_ is history: slot 2's previous task failed with exit code 137 (killed, often out of memory), and a new task replaced it. DESIRED STATE is what the managers want for the task; CURRENT STATE is what the node last reported. The number of old tasks kept per slot is the swarm's task history limit (5 by default, docker swarm update --task-history-limit).
The task lifecycle
Every task walks forward through a fixed list of states and never goes back:
| State | Meaning |
|---|---|
NEW |
created by the orchestrator |
PENDING |
resources allocated (IPs); waiting for a node. A task stuck here means no node fits (Placement Constraints) |
ASSIGNED |
the scheduler chose a node |
ACCEPTED |
the node's agent accepted it |
PREPARING |
the node pulls the image, creates networks and mounts |
READY |
everything is prepared; about to start |
STARTING |
the container is starting |
RUNNING |
the container runs (and, if it has a healthcheck, is healthy) |
COMPLETE |
exited with code 0 |
FAILED |
exited non-zero, or the healthcheck failed |
SHUTDOWN |
stopped on purpose (scale down, update, drain) |
REJECTED |
the node could not run it (for example the image pull failed) |
REMOVE |
the service was removed or scaled down; the task is being deleted |
ORPHANED |
its node has been down too long |
The model replays the life of one task that fails to pull its image and of one that runs and is later replaced by an update:
ORDER = ["NEW", "PENDING", "ASSIGNED", "ACCEPTED", "PREPARING", "READY", "STARTING",
"RUNNING", "COMPLETE", "SHUTDOWN", "FAILED", "REJECTED", "REMOVE", "ORPHANED"]
class Task:
def __init__(self, name):
self.name, self.state, self.history = name, "NEW", ["NEW"]
def advance(self, new):
if ORDER.index(new) <= ORDER.index(self.state):
print(f" {self.name}: refused {self.state} -> {new} (states only move forward)")
return
self.state = new
self.history.append(new)
t1 = Task("api.1 (bad image tag)")
for s in ["PENDING", "ASSIGNED", "ACCEPTED", "PREPARING", "REJECTED"]:
t1.advance(s)
print(" -> ".join(t1.history))
t2 = Task("api.2")
for s in ["PENDING", "ASSIGNED", "ACCEPTED", "PREPARING", "READY", "STARTING", "RUNNING"]:
t2.advance(s)
t2.advance("STARTING") # a restart never reuses the task
t2.advance("SHUTDOWN") # replaced by a rolling update
print(" -> ".join(t2.history))NEW -> PENDING -> ASSIGNED -> ACCEPTED -> PREPARING -> REJECTED
api.2: refused RUNNING -> STARTING (states only move forward)
NEW -> PENDING -> ASSIGNED -> ACCEPTED -> PREPARING -> READY -> STARTING -> RUNNING -> SHUTDOWN
Because states only move forward, "restarting a container" in Swarm always means creating a new task. That is why docker service ps shows a growing history under each slot when something is wrong.
Restart policy
When a task's container exits, the restart policy decides whether the slot gets a new task:
| Setting | CLI flag | Default | Meaning |
|---|---|---|---|
condition |
--restart-condition |
any |
none (never), on-failure (non-zero exit only), any (always) |
delay |
--restart-delay |
5s |
wait between a task ending and its replacement starting |
max_attempts |
--restart-max-attempts |
0 = unlimited |
give up after this many restarts... |
window |
--restart-window |
0 |
...counted within this window (0 = count all restarts ever) |
def run_slot(exit_codes, condition="any", max_attempts=0, window=None, delay=5, lifetime=20):
t, restarts, log = 0, [], []
for code in exit_codes:
t += lifetime # the container ran for `lifetime` seconds, then exited
outcome = "COMPLETE" if code == 0 else "FAILED"
wants = condition == "any" or (condition == "on-failure" and code != 0)
recent = [r for r in restarts if window is None or t - r < window]
if not wants:
log.append(f"t={t}s {outcome}, no restart (condition={condition})")
break
if max_attempts and len(recent) >= max_attempts:
log.append(f"t={t}s {outcome}, gave up after {len(recent)} restart(s)")
break
t += delay
restarts.append(t)
log.append(f"t={t}s {outcome} -> new task")
for line in log:
print(" " + line)
print("batch job exits 0, condition=on-failure:")
run_slot([0], condition="on-failure")
print("crash loop, condition=any, max_attempts=3:")
run_slot([1, 1, 1, 1, 1], max_attempts=3)
print("slow crashes (every 20s), max_attempts=3 within a 40s window:")
run_slot([1, 1, 1, 1, 1], max_attempts=3, window=40)
print("tight crash loop (every 2s), same policy:")
run_slot([1, 1, 1, 1, 1], max_attempts=3, window=40, lifetime=2)batch job exits 0, condition=on-failure:
t=20s COMPLETE, no restart (condition=on-failure)
crash loop, condition=any, max_attempts=3:
t=25s FAILED -> new task
t=50s FAILED -> new task
t=75s FAILED -> new task
t=95s FAILED, gave up after 3 restart(s)
slow crashes (every 20s), max_attempts=3 within a 40s window:
t=25s FAILED -> new task
t=50s FAILED -> new task
t=75s FAILED -> new task
t=100s FAILED -> new task
t=125s FAILED -> new task
tight crash loop (every 2s), same policy:
t=7s FAILED -> new task
t=14s FAILED -> new task
t=21s FAILED -> new task
t=23s FAILED, gave up after 3 restart(s)
The window changes the meaning of max_attempts from "three restarts ever" to "three restarts in a short time": with a 40-second window, old restarts age out, so a service that crashes now and then keeps being restarted, while a tight crash loop is stopped after three quick attempts.
Note: Swarm uses
deploy.restart_policy. Keys that only make sense on one host, such asbuild, are ignored bydocker stack deploy(it printsIgnoring unsupported options: …), anddocker stack configpasses them through silently, so it will not warn you. The Compose restart lesson covers the single-hostrestart:key.
Learn more: Replicated & Global Services · Inspecting Services · Kubernetes Deployments
Test yourself
A task's container exits with code 1 and the restart policy is any. What happens?
- The same task is restarted
- The task ends (FAILED) and a new task is created for the same slot
- The service is removed
- The node is drained
docker service ps api shows a task stuck in PENDING. What does that usually mean?
- The image is being pulled
- No node satisfies its constraints or resource reservations
- The container is unhealthy
- The task completed
What is the default restart condition of a Swarm service?
- none
- on-failure
- any
- unless-stopped