Cloud Native › Swarm

Stateful services in Docker Swarm with placement constraints

See how Swarm local volumes reset on node drain, how node.labels constraints block split-brain, and when to move databases outside the cluster.

Stateful services in Docker Swarm with placement constraints

A Docker Swarm service backed by a default local named volume starts with an empty volume when its node is drained and rescheduled elsewhere. This post verifies local volume stranding and node.labels placement constraints on a three-node cluster, then lays out when to use shared storage or an external database.

The local volume relocation and placement constraint tests ran on an isolated three-node docker:29-dind cluster (Docker Engine 29.10.1, linux/arm64) with one manager (swarm-mgr1), two workers (swarm-wrk1, swarm-wrk2), and alpine:3.21 containers. The shared storage (NFS/CephFS) and external database comparisons are architectural trade-offs rather than DinD benchmarks.

Why local named volumes reset after node drain

Stateless services handle node replacement well. As shown in Replicate services and move tasks with Docker Swarm, draining a worker prompts the manager to start a replacement task on another healthy node. Stateful workloads break that assumption as soon as they rely on default local volumes.

Docker’s local volume driver stores data under /var/lib/docker/volumes/<volume>/_data on a single host, just like the single-node setup covered in Docker volumes vs. bind mounts and permissions. Swarm doesn’t ship with a built-in distributed storage layer to replicate or migrate local volumes across nodes. If a task with an unpinned named volume moves to another worker, the new node creates a brand-new empty volume with the same name.

To observe this directly, I created a single-replica service with the state-data volume and no placement constraints, wrote a record on swarm-wrk1, and drained that worker.

1
2
3
4
5
6
7
8
9
10
11
12
13
# Run on the manager: create a service with an unpinned named volume
docker service create --name stateful-unpinned \
  --replicas 1 \
  --mount type=volume,source=state-data,target=/data \
  alpine:3.21 sh -c 'sleep 3600'

# Write a file inside the initial task on swarm-wrk1
docker exec <container-id-on-wrk1> \
  sh -c 'echo "order-1001:paid:created_on=swarm-wrk1" > /data/orders.log'

# Run on the manager: drain swarm-wrk1
docker node update --availability drain swarm-wrk1
docker service ps stateful-unpinned

Swarm rescheduled the task onto swarm-wrk2 in 12 seconds. Reading /data/orders.log inside the new container immediately failed.

1
2
3
4
5
6
7
8
9
10
# Rescheduled to swarm-wrk2 12 seconds after draining swarm-wrk1
NAME                      NODE         DESIRED STATE   CURRENT STATE
stateful-unpinned.1       swarm-wrk2   Running         Running less than a second ago
 \_ stateful-unpinned.1   swarm-wrk1   Shutdown        Shutdown 1 second ago

# Check /data on the new node (swarm-wrk2) -> empty volume (exit 1)
cat: can't open '/data/orders.log': No such file or directory

# Check the original state-data volume on swarm-wrk1 -> file is still intact
order-1001:paid:created_on=swarm-wrk1

The file wasn’t deleted—it stayed stranded on swarm-wrk1’s local disk. For a plain log file, that’s annoying. For PostgreSQL or MySQL, it’s dangerous: seeing an empty data directory, the entrypoint runs fresh database initialization and comes up healthy with zero rows. Once applications start writing to that empty instance, you end up with split-brain data across nodes.

Blocking empty volume initialization with node.labels constraints

If you want to keep using a local volume without risking empty initialization on another host, pin the service to a specific node using node.labels and --constraint. When that node drains or goes offline, Swarm holds the task in Pending instead of moving it to a node that doesn’t have the data.

flowchart TD
    A["swarm-wrk1 drained"] --> B{"Placement constraint?"}
    B -->|"Unpinned"| C["Moves to swarm-wrk2"]
    C --> D["Empty volume created"]
    B -->|"db==primary"| E["Stays Pending"]
    E --> F["Returns on active"]

Next, I labeled swarm-wrk1 with db=primary, pinned a new service (stateful-pinned) to that label, wrote a record to /data/ledger.log, drained swarm-wrk1, and then brought it back to active.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 1. Label swarm-wrk1 and deploy a pinned stateful service
docker node update --label-add db=primary swarm-wrk1

docker service create --name stateful-pinned \
  --replicas 1 \
  --constraint 'node.labels.db==primary' \
  --mount type=volume,source=pg-primary-data,target=/data \
  alpine:3.21 sh -c 'sleep 3600'

# 2. Write data on swarm-wrk1, then drain the node
docker exec <container-id-on-wrk1> \
  sh -c 'echo "tx-2001:committed:node=swarm-wrk1" > /data/ledger.log'
docker node update --availability drain swarm-wrk1
docker service ps --no-trunc stateful-pinned

# 3. Return swarm-wrk1 to active and verify the volume data
docker node update --availability active swarm-wrk1

While swarm-wrk1 was drained, stateful-pinned stayed Pending with a constraint error. Listing volumes matching pg-primary-data on swarm-wrk2 returned zero entries, confirming no empty volume was created there.

1
2
3
4
5
6
7
8
9
10
# Right after draining swarm-wrk1: task waits in Pending instead of moving
NAME                    NODE         DESIRED STATE   CURRENT STATE           ERROR
stateful-pinned.1                    Ready           Pending 4 seconds ago   "no suitable node (scheduling constraints not satisfied on 2 nodes; 1 node not available for new tasks)"
 \_ stateful-pinned.1   swarm-wrk1   Shutdown        Running 3 seconds ago

# Volume check on swarm-wrk2 -> 0 volumes (no empty DB init or split-brain)
DRIVER    VOLUME NAME

# After setting swarm-wrk1 back to active -> original file preserved
tx-2001:committed:node=swarm-wrk1

Once swarm-wrk1 returned to active, Swarm scheduled the task back onto the same host, reattached pg-primary-data, and /data/ledger.log still contained tx-2001:committed:node=swarm-wrk1. In a docker stack deploy file, declare the same rule under deploy.placement.constraints:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# stack.yml (excerpt: placement constraint and local volume)
services:
  db:
    image: postgres:17-alpine
    volumes:
      - pg-primary-data:/var/lib/postgresql/data
    deploy:
      replicas: 1
      placement:
        constraints:
          - node.labels.db == primary

volumes:
  pg-primary-data:

This pattern protects data integrity by trading away availability. You get zero split-brain, but the service stays down until the pinned node recovers.

Comparing three stateful storage strategies in Swarm

Most Swarm teams choose between three patterns for stateful workloads. Only the first pattern (node-pinned local volume) was directly exercised in the DinD lab above; the shared storage and external database rows summarize their operational trade-offs.

StrategyWhere data livesBehavior on node drain / failureProsLimits & caveatsBest fit
1. Node-pinned constraint (node.labels + local volume)Local disk on one pinned node (/var/lib/docker/volumes)Task stays Pending -> blocks empty DB init and split-brain (verified in lab)No extra storage infra, native local disk I/O, minimal setupDowntime until the pinned node returns (no auto-failover); disk loss requires external backupsSmall services, homelabs, internal tools that tolerate brief maintenance windows
2. External shared storage (NFS, GlusterFS, CephFS, cloud volume plugins)Network storage outside Swarm nodesTask reschedules to another node and mounts the same directoryAutomatic node failover, multi-node read/write sharing (RWX)Network latency plus flock/fsync semantics make it unsuitable for high-load RDBMS; storage itself can become a SPOFUser uploads, shared static assets, low-frequency config or log files
3. External dedicated or managed DB (RDS, Cloud SQL, dedicated HA DB cluster)Independent database host or cluster outside SwarmSwarm workers stay 100% stateless and can scale, drain, or rotate freelyDelegates backups, PITR, replication, and failover to the DB tier; keeps Swarm simpleRequires network security (TLS, firewall/VPC) and separate DB cost or operationsProduction RDBMS (PostgreSQL, MySQL) and core transactional workloads (recommended)

Each option decides what you are willing to give up during a node failure. Node pinning gives up automatic failover to keep local disk speed and simplicity. Shared storage gains task portability across nodes, but adds network I/O overhead and another stateful system to operate.

When to keep state outside Docker Swarm

Running a database inside Swarm with a placement constraint or an NFS mount can work for a homelab or a low-traffic internal app, but avoid keeping state inside Swarm when any of these apply:

  • You need automatic failover and point-in-time recovery (PITR) for PostgreSQL or MySQL: Swarm’s scheduler only maintains container counts. It doesn’t coordinate primary promotion, replication lag, or WAL fencing.
  • You plan to put an RDBMS data directory on NFS or a general-purpose distributed filesystem: Under network blips or cache pressure, relaxed flock or fsync guarantees can corrupt data or stall writes. Reserve shared filesystems for uploaded media and static files.
  • You patch or replace worker nodes frequently: Pinning state to a worker couples routine OS updates and instance replacements directly to application downtime.

Moving transactional databases to a managed service (RDS, Cloud SQL) or a dedicated HA database cluster keeps every Swarm worker disposable. You can drain, patch, and replace workers without touching persistent data.

Operational pitfalls and pre-deployment checklist

Warning: A node.labels constraint only prevents Swarm from starting an empty volume on a different node. It doesn’t protect against disk failure on the pinned host itself. Always ship backups (pg_dump or volume snapshots) off the node.

Before deploying a stateful service on Swarm, check these four items:

  • Verify placement errors immediately: A typo in node.labels.db==primary or a missing node label leaves the service silently stuck in Pending. Always run docker service ps --no-trunc <service> right after deployment to catch no suitable node messages.
  • Lock replicas to 1 for local volumes: Keep replicas: 1 fixed in your stack file and deployment pipeline so a stray docker service scale doesn’t spin up a second writer against the same volume.
  • Document the maintenance runbook: Because draining a pinned node causes immediate downtime, standardize the sequence—announce window, verify off-host backup, drain, perform maintenance, return to active, and check data—before you need it in an incident.
  • Harden the boundary for external databases: When you move the database outside Swarm, restrict DB ingress to worker node subnets via firewall or VPC rules, enforce TLS, and inject credentials through Swarm secret objects rather than plain environment variables.

References

Deploy services to a swarm
Learn how to create, manage, and use volumes instead of bind mounts for persisting data generated and used by Docker.
This post is licensed under CC BY 4.0 by the author.