TExcelTAD
Home › Docker Swarm › Volumes in a Swarm

Volumes in a Swarm

On a single host, a named volume is simple: Docker creates a directory under /var/lib/docker/volumes, and whichever container mounts it sees the same files (see Docker volumes). In a swarm, that simplicity hides a trap. A local volume lives on one node. When the scheduler moves a task to another node, the task gets a different, empty volume with the same name there. For stateless services that's fine; for a database it means "where did my data go?".

The trap, step by step

text
day 1:  db.1 on node-1 ──► volume shop_pgdata on node-1  (10 GB of orders)
day 9:  node-1 drained for a kernel update
        db.1 rescheduled on node-3 ──► volume shop_pgdata on node-3  (empty!)

Docker creates the volume on demand on whatever node the task lands on, so nothing errors: PostgreSQL simply starts with an empty data directory and initialises a new database. Let's model it:

python · try it yourself
volumes = {}                     # (node, volume name) -> files

def start_task(task, node, volume):
    key = (node, volume)
    created = key not in volumes
    data = volumes.setdefault(key, [])
    print(f"{task} on {node}: volume {volume} {'created empty' if created else 'reused'}, "
          f"{len(data)} rows visible")
    return data

data = start_task("db.1", "node-1", "shop_pgdata")
data += ["order 1", "order 2", "order 3"]

print("-- node-1 drained, task rescheduled --")
start_task("db.1", "node-3", "shop_pgdata")

print("-- with placement constraint node.labels.db == true (only node-1 has it) --")
start_task("db.1", "node-1", "shop_pgdata")
print("volumes on disk:", sorted(volumes))
db.1 on node-1: volume shop_pgdata created empty, 0 rows visible
-- node-1 drained, task rescheduled --
db.1 on node-3: volume shop_pgdata created empty, 0 rows visible
-- with placement constraint node.labels.db == true (only node-1 has it) --
db.1 on node-1: volume shop_pgdata reused, 3 rows visible
volumes on disk: [('node-1', 'shop_pgdata'), ('node-3', 'shop_pgdata')]

Three ways out

Approach How Good for Watch out
Pin the task placement constraint on a node label; the volume stays local databases on one well-backed-up node no automatic failover: if that node dies, the service waits
Shared storage volume backed by NFS/CIFS via the local driver's driver_opts, mounted on every node shared uploads, config, small apps network file systems and databases are a poor match (locking, fsync, latency)
Volume plugin / cluster volume a storage driver (cloud block storage, Portworx, a CSI plugin) that attaches the same disk to whichever node runs the task real failover for stateful services extra component to operate; check that your plugin supports Swarm

Docker Engine 23 added cluster volumes, Swarm's support for Container Storage Interface (CSI) plugins (docker volume create --driver <csi-plugin> --type mount … plus --mount type=cluster on a service). It works with docker service create, but stack files can't declare cluster volumes, and few CSI drivers document Swarm support. Many teams therefore keep databases outside the swarm (a managed database) or pinned to labelled nodes.

Volumes in a stack file

Stack volumes are namespaced like everything else: pgdata in stack shop becomes shop_pgdata. The driver_opts of the local driver are passed to mount, which is how you describe an NFS export:

compose · try it yourself
# $ docker stack config -c stack.yaml
# --- stack.yaml
services:
  db:
    image: postgres:17
    volumes:
      - pgdata:/var/lib/postgresql/data
    deploy:
      placement:
        constraints: [node.labels.db == true]
  web:
    image: ghcr.io/acme/shop-web:3.2.0
    volumes:
      - uploads:/srv/uploads
      - type: tmpfs
        target: /tmp
        tmpfs:
          size: 67108864
    deploy:
      replicas: 3
volumes:
  pgdata:
  uploads:
    driver: local
    driver_opts:
      type: nfs
      o: addr=10.0.0.50,nfsvers=4.1,rw
      device: ":/exports/shop-uploads"
version: "3.13"
services:
  db:
    deploy:
      placement:
        constraints:
          - node.labels.db == true
    image: postgres:17
    volumes:
      - type: volume
        source: pgdata
        target: /var/lib/postgresql/data
  web:
    deploy:
      replicas: 3
    image: ghcr.io/acme/shop-web:3.2.0
    volumes:
      - type: volume
        source: uploads
        target: /srv/uploads
      - type: tmpfs
        target: /tmp
        tmpfs:
          size: 67108864
volumes:
  pgdata: {}
  uploads:
    driver: local
    driver_opts:
      device: :/exports/shop-uploads
      o: addr=10.0.0.50,nfsvers=4.1,rw
      type: nfs

The short form pgdata:/var/lib/postgresql/data became a long-form mount of type: volume. Every node that runs a web task creates its own shop_uploads volume, but because all of them mount the same NFS export, they all see the same files. The tmpfs mount is RAM-backed scratch space that disappears with the task; its size is given in bytes.

Bind mounts

Bind mounts (/host/path:/container/path) work in services too, but the path must exist on every node where the task may run, or the task is rejected with invalid mount config … bind source path does not exist. That makes them useful mainly for global services that read node-level files (/var/run/docker.sock, /proc, /var/log) or together with a placement constraint.

compose · try it yourself
# $ docker stack config -c stack.yaml
# --- stack.yaml
services:
  log-shipper:
    image: fluent/fluent-bit:4.0
    volumes:
      - /var/lib/docker/containers:/var/lib/docker/containers:ro
      - type: bind
        source: /etc/machine-id
        target: /etc/machine-id
        read_only: true
    deploy:
      mode: global
version: "3.13"
services:
  log-shipper:
    deploy:
      mode: global
    image: fluent/fluent-bit:4.0
    volumes:
      - type: bind
        source: /var/lib/docker/containers
        target: /var/lib/docker/containers
        read_only: true
      - type: bind
        source: /etc/machine-id
        target: /etc/machine-id
        read_only: true

External volumes

If a volume was created outside the stack (for example restored from a backup), mark it external. The stack then uses it as is and never creates it; docker stack rm also leaves it alone. In fact docker stack rm never removes any named volumes, so data survives redeploys, and you clean up old volumes with docker volume rm on each node.

bash
$ docker volume ls --filter label=com.docker.stack.namespace=shop
DRIVER    VOLUME NAME
local     shop_pgdata
local     shop_uploads

(sample output, from one node. Run it on another node and you may see a different list.)

Which storage for which service?

A quick decision helper you can adapt:

python · try it yourself
def storage_for(service):
    if not service["stateful"]:
        return "no volume (or tmpfs for scratch)"
    if service.get("managed_db_available"):
        return "managed database outside the swarm"
    if service["needs_failover"]:
        return "volume plugin / CSI cluster volume (test failover!)"
    if service["shared_files"]:
        return "NFS-backed local volume"
    return "local volume + placement constraint on a labelled node"

for name, svc in {
    "web":     {"stateful": False},
    "uploads": {"stateful": True, "needs_failover": False, "shared_files": True},
    "db":      {"stateful": True, "needs_failover": False, "shared_files": False},
    "db-ha":   {"stateful": True, "needs_failover": True, "shared_files": False},
    "orders":  {"stateful": True, "managed_db_available": True},
}.items():
    print(f"{name:<8} -> {storage_for(svc)}")
web      -> no volume (or tmpfs for scratch)
uploads  -> NFS-backed local volume
db       -> local volume + placement constraint on a labelled node
db-ha    -> volume plugin / CSI cluster volume (test failover!)
orders   -> managed database outside the swarm

Tip: Back up volumes from the node that holds them (or from the storage system); the Swarm's own backup covers cluster state, not volume data. Kubernetes solves the "which node has my data" problem with PersistentVolumes and StorageClasses: see Persistent Volumes.

Learn more: Compose volumes · Placement Constraints · Configs

Test yourself

A replicated db service with a local named volume is rescheduled to another node. What happens to its data?

  1. Swarm copies the volume to the new node
  2. The task starts with a new, empty volume of the same name on the new node
  3. The task refuses to start
  4. The old node streams the data over the overlay

Which is the simplest way to keep a single-instance database with its local volume?

  1. Use mode: global
  2. Pin it with a placement constraint on a node label
  3. Use endpoint_mode: dnsrr
  4. Use a tmpfs mount

What does docker stack rm shop do with the volume shop_pgdata?

  1. Deletes it on every node
  2. Leaves it in place
  3. Moves it to the manager
  4. Backs it up first