Rollbacks
Sooner or later a release goes wrong: the new image crashes, fails its healthcheck, or works but has a bug. Swarm keeps the previous version of every service's spec, so going back is a single command, and with the right update config it happens automatically. This lesson covers manual and automatic rollbacks, the rollback config, and the limits of what a rollback can undo.
PreviousSpec: one step of history
Every time a service is updated, the manager saves the spec it is replacing as PreviousSpec. A rollback is simply a rolling update back to that spec. There is only one level of history: Swarm remembers "the version before the last update", not a list of releases.
$ docker service update --image ghcr.io/acme/shop-api:2.6.0 shop_api
$ docker service rollback shop_api
shop_api
rollback: manually requested rollback
overall progress: rolling back update: 4 out of 4 tasks
1/4: running [> ]
2/4: running [> ]
3/4: running [> ]
4/4: running [> ]
verify: Service shop_api converged(sample output; docker service update --rollback shop_api does the same)
Because a rollback is itself an update, it swaps the two specs. Rolling back twice brings you back to the version you rolled away from:
class Service:
def __init__(self, image):
self.spec, self.previous = {"image": image}, None
def update(self, image):
self.previous, self.spec = self.spec, {"image": image}
print(f"update -> running {self.spec['image']:<8} (previous: {self.previous['image']})")
def rollback(self):
if self.previous is None:
print("rollback -> error: service does not have a previous spec")
return
self.spec, self.previous = self.previous, self.spec
print(f"rollback -> running {self.spec['image']:<8} (previous: {self.previous['image']})")
api = Service("2.4.1")
api.rollback()
api.update("2.5.0")
api.update("2.6.0")
api.rollback() # back to 2.5.0
api.rollback() # the "previous" is now 2.6.0 againrollback -> error: service does not have a previous spec
update -> running 2.5.0 (previous: 2.4.1)
update -> running 2.6.0 (previous: 2.5.0)
rollback -> running 2.5.0 (previous: 2.6.0)
rollback -> running 2.6.0 (previous: 2.5.0)
To get from 2.6.0 back to 2.4.1 you deploy 2.4.1 as a normal update. That is why stack files with explicit, immutable image tags matter: your Git history, not the swarm, is the long-term record of what was deployed. Re-deploying an older stack file is a roll forward to an old version, and it is often the cleaner way to recover with stacks (Updating Stacks).
Automatic rollback
Set failure_action: rollback in the update config, and Swarm rolls back by itself when the update fails, that is, when new tasks fail to start, exit or become unhealthy within the monitor window more often than max_failure_ratio allows (see Rolling Updates).
def deploy(replicas, new_version_healthy, parallelism=1):
old, new = replicas, 0
log = ["updating"]
while old:
batch = min(parallelism, old)
old -= batch # stop-first
if not new_version_healthy:
log.append(f"{batch} new task(s) unhealthy within monitor -> failure ratio exceeded")
log.append("rollback_started")
restored = replicas - old # every slot not running the old spec
log.append(f"restored {restored} task(s) of the previous version; {old + restored} old, 0 new running")
log.append("rollback_completed")
return log
new += batch
log.append(f"batch ok: {old} old, {new} new")
log.append("completed")
return log
print("good release:", " | ".join(deploy(3, True)))
print("bad release: ", " | ".join(deploy(3, False)))good release: updating | batch ok: 2 old, 1 new | batch ok: 1 old, 2 new | batch ok: 0 old, 3 new | completed
bad release: updating | 1 new task(s) unhealthy within monitor -> failure ratio exceeded | rollback_started | restored 1 task(s) of the previous version; 3 old, 0 new running | rollback_completed
The bad release never reached more than one task: the first unhealthy task triggered the rollback, the other replicas were never touched, and only the one slot needed to be restored. Combined with parallelism: 1 and a healthcheck, automatic rollback keeps a broken image from ever taking down more than one replica. UpdateStatus then reads rollback_completed, with a message naming the failed task, which is what your monitoring and CI should check after a deploy.
The rollback config
A rollback is a rolling update too, so it has its own settings under deploy.rollback_config (CLI flags --rollback-*):
| Setting | Default | Meaning for a rollback |
|---|---|---|
parallelism |
1 |
tasks reverted per batch; 0 = all at once |
delay |
0s |
pause between batches |
order |
stop-first |
start-first keeps capacity while reverting |
monitor |
5s |
how long reverted tasks are watched |
failure_action |
pause |
what to do if the rollback fails: pause or continue |
max_failure_ratio |
0 |
tolerated failures during the rollback |
Rollbacks usually happen when something is broken, so they are often configured to be faster than updates: all tasks at once, or large batches, with no delay.
# $ docker stack config -c stack.yaml
# --- stack.yaml
services:
api:
image: ghcr.io/acme/shop-api:2.6.0
healthcheck:
test: ["CMD", "/app/healthcheck"]
interval: 5s
deploy:
replicas: 6
update_config:
parallelism: 1
delay: 10s
order: start-first
monitor: 30s
failure_action: rollback
rollback_config:
parallelism: 0
order: stop-first
monitor: 10s
failure_action: pauseversion: "3.13"
services:
api:
deploy:
replicas: 6
update_config:
parallelism: 1
delay: 10s
failure_action: rollback
monitor: 30s
order: start-first
rollback_config:
parallelism: 0
failure_action: pause
monitor: 10s
order: stop-first
healthcheck:
test:
- CMD
- /app/healthcheck
interval: 5s
image: ghcr.io/acme/shop-api:2.6.0
parallelism: 0 survives normalisation here (it is meaningful: "all at once"). Note what the schema does not check: the action names are plain strings to docker stack config.
# $ docker stack config -c stack.yaml
# --- stack.yaml
services:
api:
image: ghcr.io/acme/shop-api:2.6.0
deploy:
update_config:
failure_action: undoversion: "3.13"
services:
api:
deploy:
update_config:
failure_action: undo
image: ghcr.io/acme/shop-api:2.6.0
undo passes config, but the engine refuses it when the service is created or updated, so the deploy fails. Valid values are pause, continue and rollback (and only pause or continue for a rollback's own failure action).
What a rollback does not undo
A rollback restores the service spec: image, environment, resources, mounts, networks, secrets and configs as referenced by name, constraints, update settings. It does not touch anything outside it:
| Not undone | Consequence |
|---|---|
| data written to volumes or databases | a schema migration run by 2.6.0 stays; 2.5.0 must cope with it. Make migrations backward compatible (expand first, contract in a later release). |
| content behind a mutable tag | rollback restores the pinned digest, so it is safe; but redeploying :latest by hand is not |
| other services | a stack rollback does not exist; each service rolls back on its own |
| more than one step | only PreviousSpec is kept |
| config/secret contents | configs and secrets are immutable; new versions get new names, and rolling back switches the reference back (Configs, Secrets) |
A recovery checklist
- Did an automatic rollback happen?
docker service inspect -f '{{.UpdateStatus.State}} {{.UpdateStatus.Message}}' <svc>. - If the update is
paused, decide: fix forward (docker service updatewith a corrected image) ordocker service rollback. - After rolling back, update the stack file or CI variables too, otherwise the next
docker stack deploywill roll the broken version out again. - Find out why it failed:
docker service ps --no-truncon the failed tasks anddocker service logs.
Kubernetes keeps several ReplicaSet revisions and rolls back with kubectl rollout undo, optionally to a specific revision; see Kubernetes rolling updates.
Learn more: Rolling Updates · Updating Stacks · Inspecting Services
Test yourself
You updated a service from 2.4 to 2.5 and then to 2.6. What does docker service rollback run?
- 2.4
- 2.5
- The first version ever deployed
- Nothing, rollbacks need a stack
How do you make Swarm roll back automatically when new tasks fail during an update?
- Set
rollback_config.failure_action: rollback - Set
update_config.failure_action: rollback - Use
docker stack deploy --rollback - It always does by default
Release 2.6 ran a database migration and was then rolled back. What state is the database in?
- Rolled back too
- Still migrated: rollbacks only restore the service spec, so the old version must work with the new schema
- Deleted
- Restored from the last backup automatically