Secrets
Passwords, API tokens, TLS private keys: every real application has values that must not end up in an image, in Git, in docker inspect output or in a log line. Environment variables are the usual first attempt, but they leak easily: they show up in docker inspect, in crash dumps, in /proc/<pid>/environ, and child processes inherit them. Swarm secrets are built for exactly this job.
The life of a secret
docker secret create db_password - (value read from stdin)
│ mutual TLS
▼
manager: stored in the Raft log, encrypted at rest, replicated to all managers
│ only when a task of a service that was GRANTED the secret
│ is scheduled on a node
▼
worker: kept in memory, mounted on tmpfs at /run/secrets/db_password
│ task stops / service loses the grant
▼
unmounted and flushed from the node's memoryKey properties:
- Encrypted at rest and in transit. The Raft log on the managers is encrypted, and nodes talk over mutual TLS. With autolock the encryption key itself is protected too.
- Need-to-know delivery. A node receives a secret only while it runs a task of a service that was granted it. Workers never store secrets on disk.
- Files, not variables. Inside the container, the secret is a file in
/run/secrets/on an in-memory file system. Default mode0444, owner root, unless you setuid/gid/mode. - Write-only API.
docker secret inspectshows metadata but never the value. Once created, a value can only be read from inside a container that was granted it. - Immutable and small. Max 500 KB; to change a value, create a new secret.
- Services only. Plain
docker runcontainers can't use Swarm secrets.
$ printf 'S3cure-and-long!' | docker secret create db_password -
p8w2k6n0v4x7z1c5b9m3q1r7t
$ docker secret inspect db_password --format '{{.Spec.Name}} created {{.CreatedAt}}'
db_password created 2026-10-18 09:12:44.1 +0000 UTC
$ docker service create --name api --secret db_password ghcr.io/acme/shop-api:2.4.1(sample output.) Note printf rather than echo: echo would add a trailing newline to the password. And avoid typing secrets as command arguments: they land in your shell history.
Reading a secret in the app: the _FILE convention
Applications must read the file instead of an environment variable. Many official images support a _FILE suffix for this: POSTGRES_PASSWORD_FILE=/run/secrets/db_password tells the PostgreSQL image to read the password from that file. Your own code can do the same:
import os
# simulate the container's file system
FAKE_FS = {"/run/secrets/db_password": "S3cure-and-long!"}
env = {"DB_USER": "shop", "DB_PASSWORD_FILE": "/run/secrets/db_password"}
def read_setting(name):
"""Prefer NAME_FILE (a secret mount), fall back to NAME, else fail clearly."""
path = env.get(name + "_FILE")
if path:
if path not in FAKE_FS:
raise RuntimeError(f"{name}_FILE points to {path}, which does not exist")
return FAKE_FS[path].rstrip("\n")
if name in env:
return env[name]
raise RuntimeError(f"set {name} or {name}_FILE")
print("user:", read_setting("DB_USER"))
pw = read_setting("DB_PASSWORD")
print("password: (%d characters, starts with %s***)" % (len(pw), pw[0]))
try:
read_setting("API_TOKEN")
except RuntimeError as e:
print("error:", e)user: shop
password: (16 characters, starts with S***)
error: set API_TOKEN or API_TOKEN_FILE
Printing the length and first character instead of the value is a good habit when you debug secret handling.
Secrets in a stack file
# $ docker stack config -c stack.yaml
# --- stack.yaml
services:
db:
image: postgres:17
environment:
POSTGRES_USER: shop
POSTGRES_PASSWORD_FILE: /run/secrets/db_password
secrets:
- db_password
api:
image: ghcr.io/acme/shop-api:2.4.1
environment:
DB_PASSWORD_FILE: /run/secrets/db_password
secrets:
- source: db_password
uid: "1000"
gid: "1000"
mode: 0400
- source: stripe_key_v3
target: stripe_key
secrets:
db_password:
external: true
stripe_key_v3:
file: /srv/shop/secrets/stripe_keyversion: "3.13"
services:
api:
environment:
DB_PASSWORD_FILE: /run/secrets/db_password
image: ghcr.io/acme/shop-api:2.4.1
secrets:
- source: db_password
uid: "1000"
gid: "1000"
mode: 256
- source: stripe_key_v3
target: stripe_key
db:
environment:
POSTGRES_PASSWORD_FILE: /run/secrets/db_password
POSTGRES_USER: shop
image: postgres:17
secrets:
- source: db_password
secrets:
db_password:
name: db_password
external: true
stripe_key_v3:
file: /srv/shop/secrets/stripe_key
db_password is external: someone ran docker secret create before the deploy, which keeps the value out of the repository. stripe_key_v3 is read from a file on the deploying machine (keep that file out of Git, and delete it afterwards if it was generated). target: stripe_key mounts the secret stripe_key_v3 at /run/secrets/stripe_key, so the app never needs to know the version. mode: 0400 (read-only for the owner, uid 1000) comes back as 256, its decimal value, because YAML reads a leading 0 as octal.
Stacks reject the Compose-only secret source environment: (and configs' content:):
# $ docker stack config -c stack.yaml
# --- stack.yaml
services:
api:
image: ghcr.io/acme/shop-api:2.4.1
secrets: [api_token]
secrets:
api_token:
environment: API_TOKENsecrets.api_token: additional property 'environment' is not allowed
Rotating a secret
Rotation follows the same pattern as configs: versioned names plus a stable target.
$ printf 'N3w-and-even-longer!' | docker secret create db_password_v2 -
$ docker service update \
--secret-rm db_password \
--secret-add source=db_password_v2,target=db_password \
shop_api
$ docker secret rm db_password # fails while any service still uses itFor a database password there's an extra step: the database must accept the new password before the clients switch. The safe order is: (1) add the new password in the database alongside the old one (or create a second user), (2) roll the clients to the new secret, (3) remove the old password. This model walks through it and checks that no step breaks logins:
db_accepts = {"pw-v1"}
clients = {"api.1": "pw-v1", "api.2": "pw-v1", "api.3": "pw-v1"}
def check(step):
broken = [c for c, pw in clients.items() if pw not in db_accepts]
status = "OK" if not broken else "LOGIN FAILURES: " + ", ".join(broken)
print(f"{step:<34} db accepts {sorted(db_accepts)} {status}")
check("start")
db_accepts.add("pw-v2")
check("1. db accepts v1 and v2")
for task in sorted(clients): # rolling update, one task at a time
clients[task] = "pw-v2"
check(f"2. {task} now mounts db_password_v2")
db_accepts.discard("pw-v1")
check("3. db drops v1")
print("\nwrong order: switching clients first")
db_accepts, clients = {"pw-v1"}, {"api.1": "pw-v1", "api.2": "pw-v1"}
clients["api.1"] = "pw-v2"
check("api.1 switched before the db")start db accepts ['pw-v1'] OK
1. db accepts v1 and v2 db accepts ['pw-v1', 'pw-v2'] OK
2. api.1 now mounts db_password_v2 db accepts ['pw-v1', 'pw-v2'] OK
2. api.2 now mounts db_password_v2 db accepts ['pw-v1', 'pw-v2'] OK
2. api.3 now mounts db_password_v2 db accepts ['pw-v1', 'pw-v2'] OK
3. db drops v1 db accepts ['pw-v2'] OK
wrong order: switching clients first
api.1 switched before the db db accepts ['pw-v1'] LOGIN FAILURES: api.1
Secrets in Compose and Kubernetes
| Swarm secret | Compose (single host) | Kubernetes Secret | |
|---|---|---|---|
| Storage | encrypted Raft log | a file on the host (bind-mounted) | etcd (encryption at rest optional) |
| Delivery | tmpfs /run/secrets/<name> |
/run/secrets/<name> |
volume files or env vars |
| Value readable via API | no | n/a | yes, base64-encoded, for users with RBAC access |
| Update | new name, rolling update | edit the file, recreate | edit in place; mounted files update after a delay |
Compose mimics the Swarm layout so that the same app works in both (Compose configs & secrets); Kubernetes details are in Kubernetes Secrets.
Learn more: Swarm Security · Configs · Stack Files & deploy
Test yourself
Where does a task find the secret db_password by default?
- In the environment variable
DB_PASSWORD - In the file
/run/secrets/db_passwordon an in-memory file system - In
/etc/secrets/db_passwordon disk - Only through
docker secret inspect
Which command shows the value of an existing secret?
docker secret inspect --prettydocker secret show- None: the API never returns secret values
docker config inspect
What makes a secret rotation invisible to the application code?
- Using
external: true - Keeping a stable
target(e.g.db_password) while the secret name changes (db_password_v2) - Setting
mode: 0400 - Using an environment variable instead