Updating Stacks
There is no docker stack update command. To change a stack, you edit the file (or the variables it uses) and run docker stack deploy again with the same stack name. Swarm compares the new desired state with what is running and changes only what differs: services whose definition changed get a rolling update, unchanged services are left alone, new services are created. Understanding exactly what counts as "changed" saves you from surprise restarts and from updates that silently don't happen.
Deploy is declarative
$ TAG=2.5.0 docker stack deploy -c stack.yaml shop
Updating service shop_web (id: j4h1g7f2s9al)
Updating service shop_api (id: u2v7x9k1m4pq)
Updating service shop_redis (id: d8r3t6y0w5ez)(sample output.) The CLI prints "Updating service" for every service in the file; that only means it sent the spec. The manager then compares each spec with the current one, and a service whose spec is identical gets no new tasks. Here's the decision as a model:
running = {
"web": {"image": "shop-web:3.2.0", "replicas": 3, "env": {"API_URL": "http://api:9000"}},
"api": {"image": "shop-api:2.4.1", "replicas": 2, "env": {"LOG_LEVEL": "info"}},
"redis": {"image": "redis:8-alpine", "replicas": 1, "env": {}},
"old-cron": {"image": "shop-cron:1.0", "replicas": 1, "env": {}},
}
new_file = {
"web": {"image": "shop-web:3.2.0", "replicas": 3, "env": {"API_URL": "http://api:9000"}},
"api": {"image": "shop-api:2.5.0", "replicas": 2, "env": {"LOG_LEVEL": "info"}},
"redis": {"image": "redis:8-alpine", "replicas": 2, "env": {}},
"worker": {"image": "shop-worker:2.5.0", "replicas": 2, "env": {}},
}
def plan(running, new_file, prune=False):
for name in sorted(set(running) | set(new_file)):
old, new = running.get(name), new_file.get(name)
if old is None:
print(f"{name:<9} create")
elif new is None:
print(f"{name:<9} {'remove (--prune)' if prune else 'left running (not in file)'}")
elif old == new:
print(f"{name:<9} no change")
else:
changed = sorted(k for k in new if new[k] != old[k])
kind = "scale only, no restart" if changed == ["replicas"] else "rolling update"
print(f"{name:<9} {kind}: {', '.join(changed)}")
plan(running, new_file)
print("-- with --prune --")
plan(running, new_file, prune=True)api rolling update: image
old-cron left running (not in file)
redis scale only, no restart: replicas
web no change
worker create
-- with --prune --
api rolling update: image
old-cron remove (--prune)
redis scale only, no restart: replicas
web no change
worker create
Two lessons from the model:
- A service you delete from the file is not removed. It keeps running, orphaned, until you deploy with
--pruneor rundocker service rm. - Changing only
replicasscales the service without restarting the existing tasks. Almost any other change (image, environment, mounts, labels on the task template, resources) replaces the tasks according toupdate_config.
The :latest trap
If the file says image: shop-api:latest and you push a new latest, redeploying the same file changes nothing in the spec. Swarm resolves the tag to a digest at deploy time (--resolve-image always, the default), so a redeploy that sees a new digest does update the service, but nodes that can't reach the registry, or a deploy with --resolve-image never, keep the old image. Tags that change meaning make it impossible to tell what is running and to roll back. Use immutable tags (a version or Git SHA) and change the tag to deploy:
# $ docker stack config -c stack.yaml
# --- stack.yaml
services:
api:
image: ghcr.io/acme/shop-api:${API_TAG:-2.4.1}
deploy:
replicas: 4
update_config:
parallelism: 1
delay: 10s
order: start-first
failure_action: rollback
monitor: 30s
rollback_config:
parallelism: 0
order: stop-firstversion: "3.13"
services:
api:
deploy:
replicas: 4
update_config:
parallelism: 1
delay: 10s
failure_action: rollback
monitor: 30s
order: start-first
rollback_config:
parallelism: 0
order: stop-first
image: ghcr.io/acme/shop-api:2.4.1
rollback_config.parallelism: 0 means "roll back all tasks at once": when an update has gone wrong, getting back quickly matters more than doing it gently.
To redeploy without changing anything (for example to pick up a re-pushed tag or to rebalance tasks across nodes), force a task replacement on one service: docker service update --force shop_api.
Configs and secrets must change name
Configs and secrets are immutable. If you edit nginx.conf and redeploy a stack whose config has a fixed name, the deploy fails with an error saying only the labels of a config can be updated. The fix, from the Configs lesson, is a versioned name::
# $ docker stack config -c stack.yaml
# --- stack.yaml
services:
web:
image: nginx:1.27-alpine
configs:
- source: nginx_conf
target: /etc/nginx/nginx.conf
secrets:
- source: tls_key
target: shop.key
configs:
nginx_conf:
name: shop_nginx_${NGINX_CONF_REV:-1}
file: /srv/shop/nginx.conf
secrets:
tls_key:
name: shop_tls_key_${TLS_REV:-2026a}
file: /srv/shop/tls/shop.keyversion: "3.13"
services:
web:
configs:
- source: nginx_conf
target: /etc/nginx/nginx.conf
image: nginx:1.27-alpine
secrets:
- source: tls_key
target: shop.key
secrets:
tls_key:
name: shop_tls_key_2026a
file: /srv/shop/tls/shop.key
configs:
nginx_conf:
name: shop_nginx_1
file: /srv/shop/nginx.conf
Bump NGINX_CONF_REV together with the file, deploy, and web rolls over to the new config. Old config versions stay in the swarm (nothing removes them automatically), so clean up now and then:
$ docker config ls --filter name=shop_nginx_ --format '{{.Name}}'
shop_nginx_1
shop_nginx_2
shop_nginx_3
$ docker config rm shop_nginx_1 shop_nginx_2 # refused for any config still in use(sample output.)
Watching an update
$ docker stack deploy --detach=false -c stack.yaml shop
Updating service shop_api (id: u2v7x9k1m4pq)
overall progress: 2 out of 4 tasks
1/4: running [==================================================>]
2/4: running [==================================================>]
3/4: preparing [=================================> ]
4/4:(sample output.) Without --detach=false the command returns as soon as the specs are sent, and you follow progress with docker service ps shop_api or docker service inspect --format '{{json .UpdateStatus}}' shop_api. If the new version fails its healthchecks during monitor, failure_action: rollback brings back the previous spec (Rollbacks).
Networks and volumes
Some changes can't be applied to existing objects:
| Change | What happens on redeploy |
|---|---|
| add a service to an existing network | rolling update of that service |
| change a network's driver options or subnet | error: networks are immutable; remove the stack (or the network) and recreate |
change a volume's driver_opts |
ignored on nodes where the volume already exists: delete the old volume first |
| rename a service | a new service is created and the old one stays (use --prune) |
Stateful changes like these deserve a maintenance window or a blue/green move to a second stack.
A safe update routine
steps = [
("validate", "docker stack config -c stack.yaml -c prod.yaml > deployed.yaml"),
("diff", "compare deployed.yaml with the previous release's file"),
("deploy", "docker stack deploy --with-registry-auth --prune --detach=false -c deployed.yaml shop"),
("verify", "docker stack services shop; smoke-test the public URL"),
("record", "store deployed.yaml with the release tag (your rollback recipe)"),
]
for i, (name, cmd) in enumerate(steps, 1):
print(f"{i}. {name:<9} {cmd}")1. validate docker stack config -c stack.yaml -c prod.yaml > deployed.yaml
2. diff compare deployed.yaml with the previous release's file
3. deploy docker stack deploy --with-registry-auth --prune --detach=false -c deployed.yaml shop
4. verify docker stack services shop; smoke-test the public URL
5. record store deployed.yaml with the release tag (your rollback recipe)
Deploying the rendered deployed.yaml rather than the templates means the file you reviewed is the file that ran, and re-deploying the previous release's file is your rollback for the whole stack. One caveat: the rendered file has already been interpolated, so a $ escape in the template is a single $ there, and deploying the rendered file would interpolate it a second time. If your files use $, deploy the templates with the same exported variables instead.
Learn more: Rolling Updates · Rollbacks · Stack Variables & docker stack config · Kubernetes rolling updates
Test yourself
How do you update a running stack after editing its file?
docker stack update shop- Run
docker stack deploy -c stack.yaml shopagain docker stack rmthen deploy- Restart the managers
You removed the service old-cron from the stack file and redeployed. What happened to it?
- It was removed automatically
- It keeps running until you deploy with
--pruneor remove it - It was scaled to 0
- The deploy failed
You edited nginx.conf but the stack's config has a fixed name. What happens on redeploy?
- The config is updated in place
- The deploy fails because configs are immutable; use a new (versioned) name
- Only new tasks see the new file
- Nothing, the file is ignored