TExcelTAD
Home › Docker Swarm › Backup & Restore

Backup & Restore

A swarm's managers hold everything that describes your cluster: nodes, services, networks, configs, secrets, and the certificate authority that signs node certificates. With three or five managers, losing one is routine. Losing all of them (or a quorum, for good) is a disaster you recover from with a backup, or with the force-new-cluster procedure if at least one manager survived. This lesson covers both, and what a swarm backup does not contain.

What lives where

Data Where In a swarm backup?
services, networks, configs, node list, Raft log /var/lib/docker/swarm/raft on every manager yes
secrets (encrypted) inside the Raft data yes (still encrypted)
swarm CA and node certificates /var/lib/docker/swarm/certificates yes
autolock unlock key only in your password manager no: keep it separately
volume data (databases, uploads) each node's volumes or external storage no
images registries and node caches no
stack files your Git repository no (but you have them)

So a full recovery plan has three parts: the swarm state backup, the application data backups (database dumps, volume snapshots), and the stack files in Git.

Taking a swarm backup

The Raft data must not change while you copy it, so Docker is stopped on the manager for a moment:

bash
# on a manager that is NOT the leader (check MANAGER STATUS in docker node ls)
$ sudo systemctl stop docker
$ sudo tar -czf /root/swarm-$(date +%F).tar.gz -C /var/lib/docker swarm
$ sudo systemctl start docker
$ docker node ls        # wait until this manager is Reachable again

Rules of thumb:

  • Pick a follower: stopping the leader triggers an election. Stopping one manager of three still leaves a quorum of two, but never do this on a 1- or 2-manager swarm unless you accept that the control plane pauses.
  • Stop for as short a time as possible; running containers on that node are stopped too (unless live-restore is enabled in daemon.json).
  • Copy the archive off the machine, encrypt it, and record the swarm's unlock key next to it if autolock is on: without the key the backup can't be decrypted (Swarm Security).
  • Back up after significant changes (new services, rotated secrets), not just on a timer.

Application data: a backup job as a stack service

Swarm can run one-off or scheduled-from-outside jobs (mode: replicated-job): tasks that run to completion instead of being restarted. A database dump job fits well:

compose · try it yourself
# $ docker stack config -c stack.yaml
# --- stack.yaml
services:
  db-backup:
    image: postgres:17
    command: ["sh", "-c", "pg_dump -h db -U shop shop | gzip > /backups/shop-$(date +%F).sql.gz"]
    environment:
      PGPASSFILE: /run/secrets/pgpass
    secrets:
      - source: pgpass
        mode: 0400
    volumes:
      - /srv/backups:/backups
    deploy:
      mode: replicated-job
      placement:
        constraints: [node.labels.backup == true]
      restart_policy:
        condition: on-failure
        max_attempts: 2
secrets:
  pgpass:
    external: true
version: "3.13"
services:
  db-backup:
    command:
      - sh
      - -c
      - pg_dump -h db -U shop shop | gzip > /backups/shop-$(date +%F).sql.gz
    deploy:
      mode: replicated-job
      restart_policy:
        condition: on-failure
        max_attempts: 2
      placement:
        constraints:
          - node.labels.backup == true
    environment:
      PGPASSFILE: /run/secrets/pgpass
    image: postgres:17
    secrets:
      - source: pgpass
        mode: 256
    volumes:
      - type: bind
        source: /srv/backups
        target: /backups
secrets:
  pgpass:
    name: pgpass
    external: true

$(date +%F) survives interpolation as $(date +%F), so the container's shell evaluates it. A cron entry or CI schedule then re-runs the job with docker service update --force shop_db-backup.

Recovery scenarios

What you do depends on what is left. This decision helper encodes the standard procedures:

python · try it yourself
def recovery_plan(managers_total, managers_alive, have_backup):
    quorum = managers_total // 2 + 1
    if managers_alive >= quorum:
        return ["quorum intact: nothing to restore",
                "replace failed managers: `docker node demote` + `docker node rm` the dead ones,",
                "join new managers with the manager join token"]
    if managers_alive >= 1:
        return ["quorum lost, but a manager survived (its Raft data is current):",
                "on it: docker swarm init --force-new-cluster --advertise-addr <its IP>",
                "-> a 1-manager swarm with all services, secrets and workers kept",
                "promote or join new managers to get back to 3 or 5"]
    if have_backup:
        return ["all managers lost: restore from backup on a new host",
                "stop docker, replace /var/lib/docker/swarm with the backup, start docker",
                "unlock if autolock was on, then docker swarm init --force-new-cluster",
                "check services, re-join workers if they can't reconnect, add managers",
                "rotate join tokens (the old ones are in the backup)"]
    return ["all managers lost and no backup:",
            "docker swarm init on a fresh node, re-join every node,",
            "recreate secrets and configs, redeploy every stack from Git"]

cases = [(3, 2, True), (5, 2, True), (3, 0, True), (3, 0, False)]
for total, alive, backup in cases:
    print(f"== {alive}/{total} managers alive, backup: {'yes' if backup else 'no'}")
    for line in recovery_plan(total, alive, backup):
        print("   " + line)
== 2/3 managers alive, backup: yes
   quorum intact: nothing to restore
   replace failed managers: `docker node demote` + `docker node rm` the dead ones,
   join new managers with the manager join token
== 2/5 managers alive, backup: yes
   quorum lost, but a manager survived (its Raft data is current):
   on it: docker swarm init --force-new-cluster --advertise-addr <its IP>
   -> a 1-manager swarm with all services, secrets and workers kept
   promote or join new managers to get back to 3 or 5
== 0/3 managers alive, backup: yes
   all managers lost: restore from backup on a new host
   stop docker, replace /var/lib/docker/swarm with the backup, start docker
   unlock if autolock was on, then docker swarm init --force-new-cluster
   check services, re-join workers if they can't reconnect, add managers
   rotate join tokens (the old ones are in the backup)
== 0/3 managers alive, backup: no
   all managers lost and no backup:
   docker swarm init on a fresh node, re-join every node,
   recreate secrets and configs, redeploy every stack from Git

The second case is the most common real emergency: two of five managers survive a zone outage, quorum (3) is gone, and the swarm is frozen. --force-new-cluster tells the surviving manager to forget the other members and form a new single-manager Raft group with the existing state. It doesn't wipe anything, but run it on only one survivor; the other survivors must then leave (docker swarm leave --force) and re-join.

Restoring a backup, step by step

bash
# on the new manager host (ideally same IP address as the old manager)
$ sudo systemctl stop docker
$ sudo rm -rf /var/lib/docker/swarm
$ sudo tar -xzf /root/swarm-2026-10-17.tar.gz -C /var/lib/docker
$ sudo systemctl start docker
$ docker swarm unlock                       # only if autolock was enabled
Please enter unlock key:
$ docker swarm init --force-new-cluster --advertise-addr 192.168.10.11
$ docker service ls
$ docker swarm join-token --rotate worker
$ docker swarm join-token --rotate manager

(sample session.) What a restore gives back and what it doesn't:

python · try it yourself
backup_taken = {"services": {"web": "3.2.0", "api": "2.4.1"},
                "secrets": {"db_password", "stripe_key_v2"},
                "nodes": {"manager-1", "worker-1", "worker-2"}}
changes_after_backup = {"services": {"api": "2.5.0", "search": "1.0.0"},
                        "secrets": {"stripe_key_v3"},
                        "nodes": {"worker-3"}}

restored = {k: (dict(v) if isinstance(v, dict) else set(v)) for k, v in backup_taken.items()}
print("restored services:", restored["services"])
print("lost since backup :", {"services": changes_after_backup["services"],
                               "secrets": sorted(changes_after_backup["secrets"]),
                               "nodes": sorted(changes_after_backup["nodes"])})
print("fix: redeploy the current stack files from Git, recreate secrets created after the backup,")
print("     and re-join nodes that joined after it.")
restored services: {'web': '3.2.0', 'api': '2.4.1'}
lost since backup : {'services': {'api': '2.5.0', 'search': '1.0.0'}, 'secrets': ['stripe_key_v3'], 'nodes': ['worker-3']}
fix: redeploy the current stack files from Git, recreate secrets created after the backup,
     and re-join nodes that joined after it.

The backup is a point-in-time snapshot. Anything changed after it must be replayed, which is easy if every change went through stack files in Git and hard if people ran ad-hoc docker service update commands.

Practise the restore

Do a restore drill on throw-away VMs at least once: back up a test swarm, destroy its managers, restore, and check that services, secrets and workers come back. It's the only way to find out that the unlock key was not where you thought it was.

Note: In Kubernetes the equivalent is an etcd snapshot (etcdctl snapshot save), plus tools like Velero for application data: Kubernetes Architecture.

Learn more: Raft & Quorum · High Availability · Volumes in a Swarm

Test yourself

Which directory holds the swarm state you back up on a manager?

  1. /etc/docker
  2. /var/lib/docker/swarm
  3. /var/lib/docker/volumes
  4. /run/secrets

Two of five managers survive an outage. How do you get a working control plane without a backup?

  1. Wait: quorum returns automatically
  2. Run docker swarm init --force-new-cluster on one survivor, then add managers back
  3. Run docker swarm init on a new node
  4. Promote two workers

Why should you back up a follower rather than the leader?

  1. Leaders have no Raft data
  2. Stopping the leader triggers a leader election
  3. Followers have more recent data
  4. The leader's files are encrypted