TExcelTAD
Home › Docker Swarm › Rolling Updates

Rolling Updates

Deploying a new version to a swarm does not stop the service. Swarm replaces tasks a few at a time, waits for each batch to come up, watches it for a while, and only then moves on. If the new tasks fail, it can pause or roll back by itself. All of this is driven by the service's update config. This lesson explains each setting and models how an update proceeds.

Triggering an update

Any change to a service's task template starts a rolling update: a new image, environment variables, resources, mounts, constraints, labels on the container, healthcheck settings, and so on.

bash
$ docker service update --image ghcr.io/acme/shop-api:2.6.0 shop_api
shop_api
overall progress: 4 out of 4 tasks
1/4: running   [==================================================>]
2/4: running   [==================================================>]
3/4: running   [==================================================>]
4/4: running   [==================================================>]
verify: Service shop_api converged

(sample output)

With a stack, you change the file (or the image tag variable) and run docker stack deploy again; Swarm updates only the services whose spec changed (Updating Stacks). Changing only replicas is a scale, not an update: no existing task is replaced. docker service update --force replaces all tasks even when nothing changed.

The update config

Stack file (deploy.update_config) CLI flag Default Meaning
parallelism --update-parallelism 1 tasks replaced per batch (0 = all at once)
delay --update-delay 0s pause between batches
order --update-order stop-first stop-first: stop old, then start new. start-first: start new, then stop old
monitor --update-monitor 5s how long to watch each new task for failure after it starts
failure_action --update-failure-action pause pause, continue or rollback when too many tasks fail
max_failure_ratio --update-max-failure-ratio 0 fraction of updated tasks allowed to fail before failure_action triggers

A production-style setting, checked by docker stack config:

compose · try it yourself
# $ docker stack config -c stack.yaml
# --- stack.yaml
services:
  api:
    image: ghcr.io/acme/shop-api:${API_TAG:-2.6.0}
    healthcheck:
      test: ["CMD", "/app/healthcheck"]
      interval: 5s
      retries: 3
    deploy:
      replicas: 4
      update_config:
        parallelism: 1
        delay: 10s
        order: start-first
        monitor: 30s
        failure_action: rollback
        max_failure_ratio: 0
version: "3.13"
services:
  api:
    deploy:
      replicas: 4
      update_config:
        parallelism: 1
        delay: 10s
        failure_action: rollback
        monitor: 30s
        order: start-first
    healthcheck:
      test:
        - CMD
        - /app/healthcheck
      interval: 5s
      retries: 3
    image: ghcr.io/acme/shop-api:2.6.0

max_failure_ratio: 0 is missing from the output: it is the default, and zero values are dropped when the file is normalised.

One batch, step by step

For each batch of parallelism tasks, the updater:

  1. with stop-first: stops the old tasks, then starts the new ones; with start-first: starts the new tasks next to the old ones, and stops the old ones once the new ones are running;
  2. waits until the new tasks reach RUNNING, which with a healthcheck means healthy;
  3. keeps watching them for monitor; a task that fails in this window counts as an update failure;
  4. waits delay, then starts the next batch.

The model plays an update of four replicas and prints how many tasks can serve traffic at each moment. Each new task needs 8 seconds to become healthy:

python · try it yourself
def rolling_update(replicas, parallelism, order, delay, startup=8):
    old, new, t = replicas, 0, 0
    timeline = [f"t={t:>3}s serving={old + new} (old {old}, new {new})"]
    while old > 0:
        batch = min(parallelism or replicas, old)
        if order == "stop-first":
            old -= batch
            timeline.append(f"t={t:>3}s stop {batch} old  -> serving={old + new}")
            t += startup
            new += batch
            timeline.append(f"t={t:>3}s {batch} new healthy -> serving={old + new}")
        else:
            t += startup
            new += batch
            timeline.append(f"t={t:>3}s {batch} new healthy -> serving={old + new} (peak tasks {old + new})")
            old -= batch
            timeline.append(f"t={t:>3}s stop {batch} old  -> serving={old + new}")
        if old:
            t += delay
    timeline.append(f"done at t={t}s")
    return timeline

for order in ("stop-first", "start-first"):
    print(f"--- replicas=4 parallelism=1 delay=5s order={order}")
    print("\n".join(rolling_update(4, 1, order, 5)))
print("--- replicas=4 parallelism=2 delay=5s order=stop-first")
print("\n".join(rolling_update(4, 2, "stop-first", 5)))
--- replicas=4 parallelism=1 delay=5s order=stop-first
t=  0s serving=4 (old 4, new 0)
t=  0s stop 1 old  -> serving=3
t=  8s 1 new healthy -> serving=4
t= 13s stop 1 old  -> serving=3
t= 21s 1 new healthy -> serving=4
t= 26s stop 1 old  -> serving=3
t= 34s 1 new healthy -> serving=4
t= 39s stop 1 old  -> serving=3
t= 47s 1 new healthy -> serving=4
done at t=47s
--- replicas=4 parallelism=1 delay=5s order=start-first
t=  0s serving=4 (old 4, new 0)
t=  8s 1 new healthy -> serving=5 (peak tasks 5)
t=  8s stop 1 old  -> serving=4
t= 21s 1 new healthy -> serving=5 (peak tasks 5)
t= 21s stop 1 old  -> serving=4
t= 34s 1 new healthy -> serving=5 (peak tasks 5)
t= 34s stop 1 old  -> serving=4
t= 47s 1 new healthy -> serving=5 (peak tasks 5)
t= 47s stop 1 old  -> serving=4
done at t=47s
--- replicas=4 parallelism=2 delay=5s order=stop-first
t=  0s serving=4 (old 4, new 0)
t=  0s stop 2 old  -> serving=2
t=  8s 2 new healthy -> serving=4
t= 13s stop 2 old  -> serving=2
t= 21s 2 new healthy -> serving=4
done at t=21s

The trade-offs are visible:

  • stop-first never runs more tasks than replicas, so it needs no spare capacity, but every batch lowers serving capacity (to 3 of 4 here, and to 2 of 4 with parallelism: 2).
  • start-first keeps full capacity during the whole update, at the cost of running extra tasks temporarily (5 of 4 here). The nodes need room for them (reservations), and it is impossible when each task binds a fixed host port (mode: host publishing), because old and new cannot both hold it.
  • Higher parallelism is faster but riskier; the delay gives you (and the monitor) time to notice trouble between batches.
  • During a mixed phase, old and new versions serve traffic at the same time. Your app must tolerate that (compatible APIs, database migrations that work for both versions).

When new tasks fail

A new task that fails to start, exits, or becomes unhealthy within the monitor window is an update failure. When the share of failed tasks among those updated so far exceeds max_failure_ratio, the failure_action runs:

failure_action What happens UpdateStatus.State
pause (default) the update stops where it is; a mix of old and new tasks keeps running paused
continue the update carries on with the next batches anyway continues
rollback Swarm starts a rollback to the previous spec (Rollbacks) rollback_started … rollback_completed
python · try it yourself
def update(replicas, parallelism, fails, max_failure_ratio=0.0, failure_action="pause"):
    """fails: set of task numbers (1-based) whose new version fails within the monitor window."""
    updated = failed = 0
    while updated < replicas:
        batch = list(range(updated + 1, min(updated + parallelism, replicas) + 1))
        updated += len(batch)
        failed += sum(1 for n in batch if n in fails)
        ratio = failed / updated
        print(f"  batch {batch}: {failed}/{updated} failed (ratio {ratio:.2f})")
        if ratio > max_failure_ratio and failure_action != "continue":
            return f"{failure_action}d after {updated} of {replicas} tasks" if failure_action == "pause" else "rollback started"
    return "completed" + (f" with {failed} failed task(s)" if failed else "")

print("bad release, defaults (pause):")
print("  ->", update(6, 1, fails={1, 2, 3, 4, 5, 6}))
print("bad release, failure_action=rollback:")
print("  ->", update(6, 2, fails={1, 2, 3, 4, 5, 6}, failure_action="rollback"))
print("one flaky task, max_failure_ratio=0.2:")
print("  ->", update(6, 1, fails={4}, max_failure_ratio=0.2))
print("one flaky task, failure_action=continue:")
print("  ->", update(6, 2, fails={1}, failure_action="continue"))
bad release, defaults (pause):
  batch [1]: 1/1 failed (ratio 1.00)
  -> paused after 1 of 6 tasks
bad release, failure_action=rollback:
  batch [1, 2]: 2/2 failed (ratio 1.00)
  -> rollback started
one flaky task, max_failure_ratio=0.2:
  batch [1]: 0/1 failed (ratio 0.00)
  batch [2]: 0/2 failed (ratio 0.00)
  batch [3]: 0/3 failed (ratio 0.00)
  batch [4]: 1/4 failed (ratio 0.25)
  -> paused after 4 of 6 tasks
one flaky task, failure_action=continue:
  batch [1, 2]: 1/2 failed (ratio 0.50)
  batch [3, 4]: 1/4 failed (ratio 0.25)
  batch [5, 6]: 1/6 failed (ratio 0.17)
  -> completed with 1 failed task(s)

With the default max_failure_ratio: 0, the very first failure triggers the action. A small positive ratio tolerates a flaky task in a large service, but notice the third run: the flaky task was the fourth, and 1 failure out of 4 updated tasks (0.25) is above 0.2, so the update paused, although 1 out of 6 (0.17) would have been within the limit at the end. The ratio is computed over the tasks updated so far, so an early failure weighs more.

A paused update shows up like this (sample output):

bash
$ docker service inspect -f '{{.UpdateStatus.State}}: {{.UpdateStatus.Message}}' shop_api
paused: update paused due to failure or early termination of task 9yz3bq1v4kq0lzaxd0cp1x6ml

From there you can fix the cause and resume by running docker service update again with the corrected image or settings, or go back with docker service rollback shop_api.

Pitfalls checked by docker stack config

Only start-first and stop-first exist; anything else is a schema error:

compose · try it yourself
# $ docker stack config -c stack.yaml
# --- stack.yaml
services:
  api:
    image: ghcr.io/acme/shop-api:2.6.0
    deploy:
      update_config:
        order: start-last
services.api.deploy.update_config.order: value must be one of 'start-first', 'stop-first'

Recommendations

  • Always give updated services a healthcheck; without one, "the container started" is all the updater knows.
  • Use failure_action: rollback with a monitor long enough to catch slow failures (30s or more for most web apps).
  • Prefer order: start-first for stateless services with spare capacity; keep stop-first for services that must never run two versions side by side (some singletons, anything holding a lock or a host port).
  • Deploy immutable tags (2.6.0 or a digest), not latest, so that "previous version" means something.

Kubernetes Deployments do the same with maxSurge/maxUnavailable and readiness probes; see Kubernetes rolling updates.

Learn more: Rollbacks · Updating Stacks · Healthchecks & Self-Healing

Test yourself

What is the default order of a Swarm rolling update, and what does it imply?

  1. start-first: full capacity, extra tasks
  2. stop-first: an old task is stopped before its replacement starts, so capacity drops during each batch
  3. random
  4. all-at-once

Why can't order: start-first be used for a service that publishes a port in mode: host?

  1. Host mode is deprecated
  2. Old and new tasks on the same node would both need the same host port
  3. start-first only works with global services
  4. It can, without any problem

With default settings, the first new task of an update becomes unhealthy within the monitor period. What happens?

  1. The update continues
  2. The update pauses (failure_action: pause)
  3. Swarm rolls back automatically
  4. The service is deleted