Swarm Secrets Rotation in Docker
How Docker Swarm lets you replace a live credential across an entire running service without ever writing the secret to disk in plaintext, and without a single second of service downtime.
Every production system that talks to a database, calls an external API, or signs a token eventually faces the same uncomfortable question: how do you change that password, key, or certificate without breaking everything that currently depends on it? Hardcoding a credential into an image is an obvious security mistake, but even storing it as an ordinary environment variable or file leaves it exposed in ways a careful attacker can exploit. Docker Swarm’s secrets system was purpose-built to close that gap — encrypting credentials at rest, delivering them to containers only in memory, and never through a normal environment variable or writable file. Swarm secrets rotation is the natural next step: the deliberate, controlled process of replacing an already-deployed secret with a new value across every task of a running service, ideally with zero downtime and no window where the service is left holding a secret that has already been invalidated elsewhere. This guide explains how Swarm secrets actually work under the hood, and how rotation is designed to happen safely in a live, distributed cluster.
Chapter One
ACore Concepts
Before rotation makes sense, it’s worth understanding exactly what a Swarm secret is and why it behaves so differently from an ordinary environment variable.
What a Docker Swarm secret actually is
A Swarm secret is a blob of sensitive data — a password, an API key, a TLS certificate, an SSH key — that is registered once with the Swarm cluster’s manager nodes, stored encrypted, and then made available only to the specific services that have been explicitly granted access to it. Unlike an environment variable, which is often visible through simple process inspection or accidentally logged, a Swarm secret is delivered to a container as a file mounted inside an in-memory filesystem, never written to the container’s actual disk layer, and never passed as a plaintext environment variable at all.
Think of a Swarm secret like a visitor’s temporary access badge at a secure building, issued fresh at the front desk and valid only for that specific visit. The badge is never photocopied, never left lying around after the visitor leaves, and grants access only to the specific rooms that visit was approved for. Rotating a secret is like the building reissuing a completely new badge design and quietly deactivating the old one — visitors currently inside finish using their existing badge for the moment, but any new visitor gets the new one, and eventually everyone transitions over without the front desk ever needing to lock the doors while the change happens.
Why secrets are immutable by design
A detail that surprises many engineers the first time they encounter it: an existing Swarm secret’s content cannot be edited in place once created. This is a deliberate design choice, not a missing feature. If a secret’s underlying value could be silently changed while services were already referencing it by name, there would be no clear, auditable moment at which the change took effect, and no way to safely stage a transition where old and new values briefly coexist. Instead, rotation in Swarm works by creating an entirely new secret object with a new name, and then updating the service definition to reference that new secret instead of the old one — immutability at the secret level is precisely what makes the rotation process at the service level safe and predictable.
Because individual secrets cannot be edited, “rotating a secret” in Swarm really means updating a service’s configuration to swap which secret object it references, then letting Swarm’s own rolling update mechanism carry that change out across the service’s running tasks — rotation is fundamentally a service update, layered on top of secret immutability.
Scope: Swarm mode only
It is worth being precise about scope: this entire secrets and rotation system is a feature of Docker Swarm mode specifically, requiring a cluster of manager and worker nodes, and is not available to standalone containers run outside of Swarm. Organizations running plain Docker Compose without Swarm mode enabled, or a different orchestrator entirely, rely on different secret-delivery mechanisms, even though the underlying goals — encryption at rest, in-memory-only delivery, controlled rotation — are broadly similar across the container ecosystem.
Chapter Two
BArchitecture & Components
Several distinct components across the Swarm cluster cooperate to store, distribute, and rotate secrets securely.
flowchart TB
subgraph MGR["Swarm Manager Nodes"]
RAFT["Encrypted Raft Log
(secret storage)"]
end
subgraph WRK["Worker Node"]
AGENT["Swarm Node Agent"]
subgraph TASK["Service Task Container"]
TMPFS["/run/secrets/ (tmpfs, in-memory)"]
APP["Application Process"]
end
end
RAFT -->|encrypted delivery over TLS| AGENT
AGENT -->|mounts at container start| TMPFS
APP -->|reads file| TMPFS
Raft Consensus Log
Swarm manager nodes store secrets within the same encrypted, replicated Raft log used for the rest of the cluster’s state, meaning secrets are stored at rest in encrypted form and consistently replicated across manager nodes.
Mutual TLS Between Nodes
Every manager-to-worker communication in a Swarm cluster, including secret delivery, travels over mutually authenticated TLS, so a secret is never transmitted across the cluster network in plaintext.
tmpfs Mount at /run/secrets/
Once a secret reaches the target worker node, it is mounted into the container as a file under an in-memory-only filesystem, meaning it never touches the node’s or container’s persistent disk at any point.
Explicit Service Grant
A secret is only made available to a container if the service definition explicitly grants that service access to it by name; simply existing in the cluster does not make a secret visible to every service.
Rolling Update Engine
The same rolling update logic Swarm uses for deploying new image versions is reused for secret rotation, replacing tasks incrementally according to the service’s configured update policy rather than all at once.
Versioned Secret Names
Because secrets cannot be edited in place, teams commonly adopt an explicit versioning convention in the secret’s name itself, making it clear at a glance which generation of a credential any given service is currently using.
How secrets differ architecturally from Swarm configs
Swarm also offers a related but distinct object type called a config, intended for non-sensitive configuration data rather than credentials. The two share much of the same underlying delivery architecture — replicated storage on manager nodes, targeted delivery to specific services — but configs are not specially protected against being read by anyone with appropriate cluster access in the way secrets are, and configs are typically mounted onto the container’s normal filesystem rather than exclusively an in-memory one. Understanding this distinction matters because using a config where a secret was appropriate is a common and meaningful security mistake.
A closer look at what actually happens, step by step, when a secret is created, delivered, and later rotated.
From creation to delivery
When a new secret is created, its content is sent to a Swarm manager node, encrypted, and committed to the cluster’s replicated Raft log, which ensures the secret’s data survives the loss of any single manager node without ever existing in plaintext on manager disk. When a service that references that secret is scheduled onto a worker node, the manager delivers the secret’s decrypted content to that specific worker over the cluster’s mutually authenticated TLS connections, and the worker’s own node agent mounts it into the target container as a file under an in-memory tmpfs filesystem, immediately before that container’s process starts, so the application can read it as an ordinary file from the very first moment it runs.
What actually happens during a rotation
Rotation begins with creating a brand-new secret object containing the new credential value, entirely independent of the old one. The service definition is then updated to reference this new secret, typically in place of, or alongside, the old one. Swarm’s rolling update engine then begins replacing the service’s running tasks one at a time, or in whatever batch size the service’s update configuration specifies: for each task being replaced, a new task is started with the updated secret already mounted, health-checked to confirm it started successfully, and only once healthy is the corresponding old task — still running with the old secret — stopped and removed. This continues until every task in the service has been transitioned, with the service as a whole remaining available to traffic throughout the entire process.
sequenceDiagram
participant Op as Operator
participant Mgr as Swarm Manager
participant Old as Old Task (secret v1)
participant New as New Task (secret v2)
Op->>Mgr: create new secret (v2)
Op->>Mgr: update service to reference secret v2
Mgr->>New: schedule replacement task with secret v2
New-->>Mgr: health check passes
Mgr->>Old: stop and remove old task
Note over Old,New: service remains available
to traffic throughout
Mgr->>Mgr: repeat for each remaining task
Why the old secret must survive until rotation completes
A crucial internal-working detail: the old secret object must remain available in the cluster for as long as any task still referencing it is running, which is why deleting the old secret immediately upon creating the new one is a common and serious mistake. Because rotation proceeds gradually across a service’s tasks — not instantaneously across all of them at once — there is necessarily a window during which some tasks are still using the old secret while others have already moved to the new one, and removing the old secret prematurely would cause the not-yet-updated tasks to fail outright the next time they needed to be rescheduled.
Chapter Four
DData Flow & Lifecycle
Tracing a secret’s complete journey from creation through active use, rotation, and eventual safe removal.
Secret Created
The new credential is submitted to a Swarm manager, encrypted, and committed to the replicated cluster state, but not yet attached to any running service.
Service References the Secret
A service definition is created or updated to grant itself access to the secret, at which point Swarm begins delivering it to that service’s tasks.
Steady-State Use
Every running task of the service has the secret mounted as an in-memory file, read by the application as needed for the service’s normal operation.
Rotation Initiated
A new secret is created, and the service is updated to reference it, triggering Swarm’s rolling update mechanism.
Gradual Transition
Tasks are replaced incrementally, with old and new secret versions coexisting across the service until every task has transitioned.
Old Secret Safely Removed
Once confirmed that no running task anywhere in the cluster still references the old secret, it can be deleted from the cluster entirely, completing the rotation.
Coordinating rotation with the credential’s source of truth
In practice, a full rotation lifecycle usually needs to be coordinated with whatever external system actually issues or validates the credential — a database’s own user-password store, a certificate authority, an external API provider’s key management console. The safest sequencing generally introduces the new credential at the source first (so both old and new values are simultaneously valid there), then rotates the Swarm secret and lets tasks transition, and only invalidates the old credential at the source once the rotation across the entire Swarm service has fully completed — mirroring, at the external system, the same overlap window Swarm itself creates internally during the rolling update.
Chapter Five
EAdvantages, Disadvantages & Trade-offs
Swarm’s approach to secrets rotation trades some operational complexity for strong safety guarantees — a trade-off worth examining explicitly.
Advantages
- Rotation can be performed with zero service downtime, thanks to the rolling update mechanism handling the transition incrementally
- Secrets never touch persistent disk at any point in their lifecycle, sharply reducing the risk of accidental exposure through backups, logs, or disk forensics
- Immutable secret objects eliminate an entire class of race conditions where a secret’s value changes mid-use without any clear transition point
- The same familiar rolling update mechanism used for ordinary deployments is reused for rotation, meaning no separate, specialized tooling is required
- Access is explicitly scoped per service, so rotating one service’s secret does not require touching unrelated services that happen to share the same underlying credential type
Disadvantages
- Because secrets are immutable, every rotation necessarily creates a new object, requiring a deliberate naming or versioning discipline to avoid clutter and confusion over time
- Coordinating the overlap window with an external credential source (a database, an API provider) adds real operational complexity beyond what Swarm itself automates
- Confirming that the old secret is truly safe to delete requires positively verifying no task anywhere still references it, which is an extra manual or scripted step Swarm does not fully automate on its own
- Rotation is scoped to Swarm mode specifically, so organizations mixing Swarm with other orchestration or standalone Docker usage cannot rely on one unified rotation mechanism
- A rolling update’s pacing, while safe, means a rotation across a very large service can take measurably longer than an instantaneous credential swap would
The overlap window as the central trade-off
The single most important trade-off to internalize is this: safe, zero-downtime rotation absolutely requires a period during which both the old and new credential values are simultaneously valid, both within Swarm’s own rolling update and at whatever external system issued the credential in the first place. Organizations sometimes resist this on the assumption that a credential should be invalidated the instant a replacement exists, but insisting on zero overlap is fundamentally incompatible with zero downtime — one of those two goals must yield, and in the overwhelming majority of production systems, a brief, carefully bounded overlap window is the far more acceptable trade.
The overlap window should be as short as operationally safe, not as short as theoretically possible — confirm rotation has genuinely completed across every task before invalidating the old credential at its source, rather than invalidating it on a fixed timer that assumes, but never verifies, the rotation finished in time.
Chapter Six
FSecurity
Secrets rotation exists specifically as a security practice, and understanding its guarantees — and its limits — matters as much as understanding the mechanics.
Why rotation matters even without a known compromise
Regularly rotating credentials, even in the complete absence of any known or suspected compromise, is a defense-in-depth practice that limits the value of a credential to an attacker who may have obtained it through a channel that was never detected — a leaked log line from years ago, a misconfigured backup, a departed employee’s still-valid local copy. A credential that is rotated on a predictable schedule has a naturally bounded useful lifetime for anyone who acquired it improperly, regardless of whether the legitimate operators ever learn that acquisition happened at all.
Regularly rotating a Swarm secret is like a bank periodically reissuing every customer’s debit card number, even for customers who have reported no fraud. It’s not a reaction to a known theft — it’s an acknowledgment that some number of card details inevitably leak through channels the bank will never fully see, and a fixed rotation schedule caps how long any one leaked number stays useful to whoever obtained it.
What rotation does not protect against
It is worth being precise about the limits of this mechanism. Secrets rotation protects the credential itself from having unbounded useful life, but it does nothing to protect against an attacker who has already compromised a running container and can simply read whatever secret is currently mounted at that exact moment — rotation changes which secret is valid over time, not whether a currently-compromised process can read the currently-valid one. Similarly, rotation does not substitute for restricting which services are granted access to a given secret in the first place; a secret rotated regularly but overexposed to services that never actually need it is still a meaningfully larger attack surface than necessary.
Context
A security audit found that several production database credentials, delivered via Swarm secrets, had never been rotated since the services were originally deployed, some over two years earlier.
Decision
A mandatory 90-day rotation cadence was adopted for all database and external API credentials delivered as Swarm secrets, automated through a scheduled process that creates the new secret, updates the service, and verifies full rollout before invalidating the old credential at its source.
Consequence
Rotation became a routine, low-drama, automated event rather than a rare, manually coordinated one, and the organization’s maximum credential exposure window shrank from an effectively unbounded period to a predictable 90 days.
Chapter Seven
GMonitoring, Logging & Metrics
Confirming a rotation genuinely completed, and catching a failed or stalled one, requires watching the right signals throughout the process.
What to watch during an active rotation
The most important signal during an active rotation is straightforward: the count of a service’s tasks still referencing the old secret versus the new one, which should monotonically move toward zero old-secret tasks as the rolling update proceeds. A rotation that stalls partway — some tasks successfully transitioned, others stuck — typically indicates a task repeatedly failing its health check after being started with the new secret, which is a strong signal that the new credential itself may be invalid or that the application cannot yet authenticate with it, rather than a Swarm-level problem.
| Signal | Healthy Rotation | Problem Rotation |
|---|---|---|
| Old-secret task count | Steadily decreasing to zero | Stuck above zero, not decreasing |
| New task health checks | Passing consistently | Repeatedly failing after replacement |
| Service availability | Unaffected throughout | Degraded as tasks fail and restart |
| Application auth errors | None observed | Spike immediately after rotation begins |
Confirming completion before cleanup
Before deleting the old secret object, the safest practice is explicitly confirming, not assuming, that zero running tasks anywhere in the cluster still reference it — a check that should be automated as part of any rotation pipeline rather than performed on faith after a fixed waiting period. Because Swarm distributes tasks across potentially many worker nodes, a manual, ad-hoc check on a single node is not sufficient evidence that rotation has genuinely completed cluster-wide.
Deleting the old secret before every task has genuinely transitioned is one of the most disruptive mistakes possible in this process: any task still referencing the deleted secret will fail the next time it needs to be rescheduled, and because Swarm tasks are rescheduled for many unrelated reasons (node failure, scaling, routine maintenance), this failure can surface unexpectedly, well after the rotation appeared to be finished and forgotten.
Chapter Eight
HDesign Patterns & Anti-patterns
Recurring approaches teams use to make secrets rotation a routine, low-risk operation, and the recurring mistakes that turn it into an incident instead.
Versioned Secret Naming
Encoding an explicit version number or date into each secret’s name at creation, making it immediately clear which generation of a credential any given service is currently bound to, without needing to inspect its actual content.
Automated Rotation Pipelines
Scripting the full rotation lifecycle — creating the new secret, updating the service, verifying complete rollout, invalidating the old credential at its source, and finally deleting the old secret — as a single, repeatable, auditable pipeline rather than a manual, ad-hoc sequence of commands.
Dual-Valid Credentials at the Source
Coordinating with the credential’s source system (a database, an identity provider) to accept both the old and new value simultaneously during the Swarm rotation window, mirroring Swarm’s own internal overlap guarantee.
Deleting the Old Secret Immediately
Removing the previous secret object the moment the new one is created, without confirming every task has actually transitioned, risking failures on any task rescheduled before the rotation genuinely completes.
Using Configs Instead of Secrets for Sensitive Data
Storing genuinely sensitive credentials as Swarm configs rather than secrets, losing the stronger in-memory-only delivery and access protections that secrets specifically provide.
Pattern in practice: scheduled, unattended rotation
Mature organizations commonly run credential rotation as a fully unattended, scheduled process — no human manually triggers each individual rotation — with the pipeline itself responsible for verifying success at each stage and alerting a human only if a step fails or stalls, turning what was once a rare, high-stress manual operation into routine, low-visibility background maintenance.
Concrete, practical guidance for rotating Swarm secrets confidently and repeatedly, without turning routine maintenance into a production incident.
Verify the new secret works before rotating widely
Confirm the new credential is valid and functional against its target system before beginning the service-wide rollout, catching a bad value before it propagates across every task.
Automate the full lifecycle, including verification
Script creation, rollout, completion verification, and old-secret cleanup as one coordinated pipeline rather than relying on manual, easy-to-skip steps in between.
Maintain an overlap window at the credential’s source
Ensure whatever system issued the credential accepts both old and new values for the duration of the Swarm rotation, avoiding a mismatch where Swarm’s rollout outpaces the source system’s own transition.
Rotating without a rollback plan
Starting a rotation without a clear, tested way to revert a service back to the old secret if the new one turns out to be broken partway through the rollout.
Letting rotated secrets accumulate unreviewed
Never cleaning up old, no-longer-referenced secret objects, leaving a growing, confusing pile of retired credentials in the cluster with no clear indication of which are genuinely safe to delete.
Treating rotation as purely a Swarm-side concern
Forgetting that the credential’s source system also needs its own coordinated transition, not just the Swarm service definition.
Chapter Ten
JReal-World & Industry Examples
Secrets rotation discipline shows up wherever organizations run stateful services that must never fully halt for routine credential maintenance.
Regulated Credential Rotation Cadences
Financial and other regulated organizations frequently operate under explicit compliance requirements mandating credential rotation on a fixed schedule, making automated, zero-downtime rotation a genuine regulatory necessity rather than an optional best practice.
Multi-Tenant API Key Rotation
Software platforms serving many customers commonly rotate the internal API keys and database credentials backing their own multi-tenant services on a routine schedule, treating rotation as a standard operational task rather than an emergency response.
Rapid Rotation After a Suspected Leak
Organizations with a well-practiced, automated rotation pipeline can respond to a suspected credential leak dramatically faster than those attempting a manual rotation for the first time under incident pressure, turning a potentially prolonged exposure window into a short, well-understood one.
Bridging Old Systems into Modern Rotation
Teams integrating older, external systems that do not natively support dual-valid credentials during a transition period often build a thin compatibility layer specifically to preserve Swarm’s zero-downtime rotation guarantee even when the external system’s own support for graceful rotation is limited.
Chapter Eleven
KFrequently Asked Questions
Chapter Twelve
LSummary and Key Takeaways
Swarm secrets rotation turns credential replacement from a risky, disruptive event into a routine, verifiable, zero-downtime operation.
Key Takeaways
- Docker Swarm secrets are encrypted at rest, delivered over mutually authenticated TLS, and mounted into containers only through an in-memory tmpfs filesystem, never touching persistent disk.
- Secrets are immutable once created; rotation works by creating a new secret object and updating the service to reference it, not by editing an existing secret’s value.
- Rotation is carried out through Swarm’s normal rolling update mechanism, replacing tasks incrementally so old and new secret versions briefly coexist without causing service downtime.
- A safe overlap window — where both old and new credential values remain valid, both within Swarm and at the credential’s external source system — is a necessary trade-off for achieving zero-downtime rotation.
- The old secret must not be deleted until every task in the cluster has been positively confirmed to have transitioned to the new one, since premature deletion can cause unexpected failures on later task rescheduling.
- Mature organizations treat rotation as a fully automated, scheduled pipeline rather than a rare manual event, which both reduces routine operational risk and dramatically improves response speed during an actual suspected credential leak.