Swarm Security
Swarm is "secure by default" in a few important ways: nodes authenticate each other with certificates, control traffic is encrypted, and secrets are stored encrypted. But defaults only cover the plumbing. A swarm is still a system where anyone with access to a manager's Docker API controls every node, so this lesson covers both what Swarm does for you and the knobs you should turn yourself.
The built-in PKI
When you run docker swarm init, the first manager creates a root certificate authority (CA). Every node that joins gets a node certificate signed by it; the certificate carries the node's ID and role (manager or worker). All communication between nodes uses mutual TLS: both sides prove who they are, and a worker certificate can't be used to act as a manager.
swarm root CA (on the managers)
├── manager-1 cert (CN=<node id>, OU=swarm-manager)
├── manager-2 cert
├── worker-1 cert (OU=swarm-worker)
└── worker-2 cert
every node-to-node connection: mutual TLSJoin tokens
A node proves it may join with a join token: SWMTKN-1-<CA fingerprint>-<secret>. The first part lets the new node verify it's talking to the right swarm (protection against man-in-the-middle), the second part authorises it. There are two tokens, one for workers and one for managers. Treat the manager token like a root password.
$ docker swarm join-token -q worker
SWMTKN-1-3pu6hszjas19xyp7ghgosyx9k8atbfcr8p2is99znpy26u2lkl-1awxwuwd3z9j1z3puu7rcgdbx
$ docker swarm join-token --rotate worker # old token stops working for NEW joins(sample output.) Rotating a token doesn't affect nodes that already joined. Rotate whenever a token may have leaked (pasted in a chat, committed to a repository) and routinely after onboarding batches of nodes.
Certificate rotation
Node certificates expire, by default after 90 days, and nodes renew them automatically while they are connected. To avoid all nodes hammering the CA at the same moment, each node renews at a randomised point in the second half of its certificate's lifetime (swarmkit picks a moment between roughly 50% and 80% of the validity). This model, with a seeded random generator, shows a year of renewals for three nodes:
import random
random.seed(7)
EXPIRY_DAYS = 90
def timeline(node, joined_day, days=365):
issued, events = joined_day, []
while True:
renew_at = issued + EXPIRY_DAYS * random.uniform(0.5, 0.8)
if renew_at > days:
break
events.append(round(renew_at))
issued = renew_at
return events
for node, joined in [("manager-1", 0), ("worker-1", 3), ("worker-2", 40)]:
days = timeline(node, joined)
gaps = [b - a for a, b in zip([joined] + days, days)]
print(f"{node:<10} renewals on day {days}")
print(f"{'':<10} days between renewals {gaps} (always < {EXPIRY_DAYS})")manager-1 renewals on day [54, 103, 165, 212, 272, 327]
days between renewals [54, 49, 62, 47, 60, 55] (always < 90)
worker-1 renewals on day [62, 108, 164, 211, 259, 315]
days between renewals [59, 46, 56, 47, 48, 56] (always < 90)
worker-2 renewals on day [88, 139, 201, 272, 332]
days between renewals [48, 51, 62, 71, 60] (always < 90)
Every gap stays well below 90 days, so a node never runs on an expired certificate unless it is offline for longer than the remaining validity. A node that was powered off for months can't rejoin with its old certificate; you remove it and join it again.
$ docker swarm update --cert-expiry 720h0m0s # 30 days instead of 90
$ docker swarm ca --rotate # new root CA, all nodes re-issuedRotating the root CA (docker swarm ca --rotate) is the response to a compromised manager: the swarm issues a new CA, gradually re-issues every node certificate, and then stops trusting the old CA. It also rotates the join tokens, since they contain the CA fingerprint.
Autolock: protecting the keys at rest
The Raft log on each manager is encrypted, but by default the key that decrypts it is stored on the same disk, so a stolen manager disk (or backup) reveals every secret. Autolock moves that key out: managers keep it only in memory, and after a Docker restart a manager stays locked until someone supplies the unlock key.
$ docker swarm update --autolock=true
Swarm updated.
To unlock a swarm manager after it restarts, run the `docker swarm unlock`
command and provide the following key:
SWMKEY-1-WuYH/aGb4j8u7cVhJ4dVcjCNgQoSs6pF4j1r0GZ2Z2Q
$ sudo systemctl restart docker
$ docker node ls
Error response from daemon: Swarm is encrypted and needs to be unlocked before it can be used.
$ docker swarm unlock
Please enter unlock key:(sample output.) The trade-off is operational: every manager restart now needs a human (or a secure automation) to unlock it. Store the key in a password manager, rotate it with docker swarm unlock-key --rotate, and keep the old key until all managers have restarted with the new one.
Hardening checklist
| Area | Default | Do this |
|---|---|---|
| Docker API on managers | Unix socket, root-equivalent | never expose TCP 2375; restrict who is in the docker group; use SSH or TLS-protected contexts for remote admin |
| Manager role | managers also run workloads | docker node update --availability drain on managers |
| Data on overlays | only control traffic is encrypted | encrypted driver option on networks carrying sensitive data (Overlay Networks) |
| Firewall | everything open | allow 2377/tcp only between nodes, 7946 tcp/udp and 4789/udp only between nodes, ESP for encrypted overlays |
| Join tokens | valid forever | rotate after use or leaks |
| Raft key | on disk | autolock |
| Images | tags can change | pin by digest, scan images, use a private registry with --with-registry-auth |
| Docker socket in services | not mounted | mount it only in services that need it (proxies, agents), read-only, on managers, ideally through a socket proxy |
Hardening a service in the stack file
Container-level hardening (Docker security) carries over to services, with one exception to remember:
# $ docker stack config -c stack.yaml
# --- stack.yaml
services:
api:
image: ghcr.io/acme/shop-api@sha256:3f1c0d6a9e8b7c5d4e3f2a1b0c9d8e7f6a5b4c3d2e1f0a9b8c7d6e5f4a3b2c1d
user: "10001:10001"
read_only: true
cap_drop: [ALL]
cap_add: [NET_BIND_SERVICE]
security_opt: [no-new-privileges:true]
volumes:
- type: tmpfs # writable scratch space for a read-only container
target: /tmp
secrets:
- db_password
networks: [back]
networks:
back:
driver: overlay
driver_opts:
encrypted: "true"
secrets:
db_password:
external: trueversion: "3.13"
services:
api:
cap_add:
- NET_BIND_SERVICE
cap_drop:
- ALL
image: ghcr.io/acme/shop-api@sha256:3f1c0d6a9e8b7c5d4e3f2a1b0c9d8e7f6a5b4c3d2e1f0a9b8c7d6e5f4a3b2c1d
networks:
back: null
read_only: true
secrets:
- source: db_password
security_opt:
- no-new-privileges:true
user: 10001:10001
volumes:
- type: tmpfs
target: /tmp
networks:
back:
driver: overlay
driver_opts:
encrypted: "true"
secrets:
db_password:
name: db_password
external: true
docker stack config accepts all of it, but security_opt is one of the options docker stack deploy ignores ("Ignoring unsupported options: security_opt"), so no-new-privileges must be set another way: as the daemon default ("no-new-privileges": true in each node's daemon.json). The rest (non-root user, read_only root file system, dropped capabilities, image pinned by digest) is applied to every task.
Who can do what?
Swarm has no built-in users or roles: whoever can talk to a manager's Docker API is an administrator of the whole cluster, including the power to run a privileged container on any node. That's a major difference from Kubernetes RBAC. Practical consequences:
people = {
"alice (platform admin)": {"ssh_manager": True, "docker_group": True},
"bob (developer)": {"ssh_manager": False, "docker_group": False, "ci_deploys": True},
"ci-runner": {"ssh_manager": True, "docker_group": True},
"carol (support)": {"ssh_manager": True, "docker_group": False},
}
for who, p in people.items():
if p.get("docker_group"):
power = "FULL control of every node (treat as root)"
elif p.get("ci_deploys"):
power = "deploys only through reviewed CI pipelines"
else:
power = "can log in, but no Docker API access"
print(f"{who:<24} {power}")alice (platform admin) FULL control of every node (treat as root)
bob (developer) deploys only through reviewed CI pipelines
ci-runner FULL control of every node (treat as root)
carol (support) can log in, but no Docker API access
Keep the list of people and systems with manager access short, deploy through CI with reviewed stack files, and audit with docker events and the managers' system logs (Logging & Monitoring).
Learn more: Secrets · Backup & Restore · Kubernetes security contexts
Test yourself
What does docker swarm join-token --rotate worker affect?
- It disconnects all workers
- New joins must use the new token; existing workers are unaffected
- It rotates all node certificates
- It rotates the unlock key
What problem does autolock solve?
- Nodes joining without a token
- The Raft encryption key being stored on the manager's disk next to the encrypted data
- Expired node certificates
- Unencrypted overlay traffic
Which hardening option in a stack file is ignored by docker stack deploy?
read_onlyusercap_dropsecurity_opt