Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Docker Secrets and Configs: Secure Management in Compose and Production

Compose secrets are bind mounts, not encryption; Swarm secrets are tmpfs. How to keep credentials out of ENV, ARG and image layers, and rotate them.

~5 min readDocker
#Docker#Security#DevOps
3D illustration of encrypted secret credentials mounted in-memory into isolated container vaults with no plaintext leaks

Quick Summary

A Docker secret is a small blob — a password, a TLS key, an API token — that Docker delivers to the container as a file under /run/secrets/, never as an environment variable and never inside an image layer. A config is the same mechanism for non-sensitive material: an nginx config, a certificate bundle, a properties file. Both are mounted read-only at start, and both exist to keep plaintext out of docker inspect, out of docker history, and out of your repository.

The security of each depends entirely on where it comes from. Under Swarm, docker secret create stores the value encrypted in the Raft log of the manager nodes, and only services that declare the secret receive it, mounted from a tmpfs. In plain Compose without Swarm, a top-level secrets: entry backed by file: is a bind mount — the file stays on the host, docker inspect shows the path, and nothing is encrypted. That is still better than an ENV, but calling it encrypted would be wrong.

Three habits cover most of the ground: keep secrets out of ARG and ENV, read them from files in the entrypoint, and rotate by creating a new secret rather than editing an old one.

Basic syntax and query signatures

yaml
# compose.yaml — Swarm-independent (file-backed), works with docker compose up services: api: image: example/api:1.4.2 secrets: - db_password - source: tls_key target: server.key mode: 0400 configs: - nginx_conf environment: DB_PASSWORD_FILE: /run/secrets/db_password secrets: db_password: file: ./secrets/db_password.txt tls_key: environment: TLS_PRIVATE_KEY # value read from the host environment # tls_key: # external: true # Swarm: use an existing secret configs: nginx_conf: file: ./nginx/nginx.conf
bash
# Swarm secrets docker swarm init printf '%s' "$DB_PASSWORD" | docker secret create db_password - docker secret ls docker secret inspect db_password --pretty docker service create --name api --secret db_password example/api:1.4.2 docker service update --secret-rm db_password --secret-add db_password_v2 api
dockerfile
# Build-time secret, BuildKit only — never lands in a layer # syntax=docker/dockerfile:1.7 RUN --mount=type=secret,id=npmrc,target=/root/.npmrc \ npm ci --omit=dev
bash
docker buildx build --secret id=npmrc,src=$HOME/.npmrc -t example/api .
sh
# entrypoint: read the secret file, export it, exec the app #!/bin/sh set -eu if [ -z "${DB_PASSWORD:-}" ] && [ -f /run/secrets/db_password ]; then DB_PASSWORD="$(cat /run/secrets/db_password)" export DB_PASSWORD fi exec "$@"

Key comparison table

Secret (Compose, file:)Secret (Swarm)ConfigBuild secret (--mount=type=secret)
Stored encryptedNoYes, in the Raft logNoNo, ephemeral mount
Mounted asBind mount at /run/secrets/<name>tmpfs at /run/secrets/<name>Bind mount at /<name> or targettmpfs during that RUN only
Visible in docker inspectThe host pathThe secret ID, not the valueThe host pathNothing after the build
Available to docker runOnly via Composedocker run --secret with a Swarm secretOnly via ComposeBuild only
Survives container exitYes, file on hostYes, in Swarm stateYes, file on hostNo
RotationReplace the host file and restartCreate new, update service, remove oldReplace and restartRebuild with the new value
Default mode0444, uid/gid 00444, uid/gid 004440400-ish via mode=
Leak channelENVARGCOPY in a layerBind mountSwarm secret
docker inspectValue visibleValue visible—Path visibleNot visible
docker history—Value visibleValue recoverable——
/proc/1/environ in containerYes———No
Image pushed to a registryYesYesYesNoNo

Practical edge cases and deep dives

1. ENV and ARG are the leak

dockerfile
# all three leak the value into the image ARG NPM_TOKEN ENV NPM_TOKEN=$NPM_TOKEN RUN echo "//registry.npmjs.org/:_authToken=$NPM_TOKEN" > /root/.npmrc && npm ci # recovered later by anyone with the image docker history --no-trunc example/api:1.4.2 | grep -i token

ENV values persist in the image config and appear in docker inspect, so any process in the container — including a compromised one — can read them from its own environment. ARG values are recorded in the image history, which the registry serves to anyone who can pull the tag. BuildKit's --mount=type=secret mounts the file only for the duration of that RUN and keeps it out of the layer and the history. For runtime, the file mount under /run/secrets is what keeps the value out of the environment.

2. Compose secrets are not encrypted — check before you claim they are

bash
docker compose up -d docker inspect $(docker compose ps -q api) --format '{{json .Mounts}}' | jq

The output shows a bind mount with "Source": "/home/deploy/app/secrets/db_password.txt" and a destination under /run/secrets/. Anyone who can run docker inspect — which on a default install is anyone in the docker group, effectively root — can read the source path, and the file itself is readable by the container's user because the default mode is world-readable. Tighten it:

yaml
secrets: db_password: file: ./secrets/db_password.txt

File permissions on the host are the control, not Docker: chmod 600 and ownership by the deploying user. Under Swarm the value is genuinely opaque — docker secret inspect returns metadata only — and the tmpfs mount disappears with the container.

3. Applications that only read environment variables

Most images accept either DB_PASSWORD or DB_PASSWORD_FILE, but plenty accept only the environment variable. The wrapper pattern above bridges them; the alternative is env_file, which puts the value straight into the container environment and back into docker inspect. For the official Postgres, MySQL and Redis images, the _FILE variants already exist (POSTGRES_PASSWORD_FILE, MYSQL_ROOT_PASSWORD_FILE), and using them is the difference between a credential visible in docker inspect and one that is not.

yaml
services: db: image: postgres:16 environment: POSTGRES_PASSWORD_FILE: /run/secrets/pg_password POSTGRES_USER: app secrets: [pg_password]

4. Rotation under Swarm

A Swarm secret is immutable. Rotation means creating db_password_v2, updating the service to mount it, and removing the old one — in that order, because removal fails while a service still references it:

Error response from daemon: secret db_password is in use by the following service: api

docker service update --secret-rm old --secret-add new api performs the swap and restarts the tasks; the config file name changes unless you map target:. Map it, so the application keeps reading /run/secrets/db_password and no code change is needed:

bash
docker service update \ --secret-rm db_password \ --secret-add source=db_password_v2,target=db_password \ api docker secret rm db_password

The removal will still fail if another service or a stopped service definition references the old secret. docker service ls plus docker service inspect --format '{{json .Spec.TaskTemplate.ContainerSpec.Secrets}}' finds the holders.

5. Configs are for files, not for every setting

A config is mounted at /<config_name> by default, which surprises people who expect /etc/nginx/nginx.conf. Set the target explicitly, and remember that configs are writable only at creation: changing the host file does not update containers until they are recreated. For a hot-reloadable config, mount it as a bind mount in development and a config in production, and make the reload explicit (docker kill -s HUP), because neither Docker nor nginx will notice the file changed.

6. Non-root containers and file modes

A secret mounted 0444 is readable by every user in the container, which is often what you want for a non-root app. If you set mode: 0400 and the container runs as uid 1000, the file is owned by root and the app cannot read it:

cat: /run/secrets/tls_key: Permission denied

Either keep 0444 (and accept that any process in the container can read it — they are in the same security boundary anyway) or set the owning uid with a sourced secret under Swarm and uid=/gid=/mode= options. There is no way to make a secret readable by one process and not another inside a single container; that requires separate containers.

Common mistakes and runtime errors

Error or symptomCauseFix
This node is not a swarm managerdocker secret used without docker swarm initSwarm mode, or use Compose file: secrets
secret ... is in use by the following serviceRemoving a secret still referencedUpdate the service to drop it first
cat: /run/secrets/x: Permission deniedMode 0400 with a non-root userUse 0444, or uid/gid/mode
Secret visible in docker inspectCompose file: secret is a bind mountAccept it, or move to Swarm secrets
Token found in docker historyARG used for a credentialBuildKit --mount=type=secret
Application reads an empty passwordEnv var set but entrypoint uses the file (or vice versa)Standardise on _FILE variables
docker config shows the file path but the container sees nothingWrong targetMount at the path the app reads, or symlink
Secret works locally, fails in CIThe secrets/ file is gitignored and not createdInject in CI with environment: or an external secret
Old password still accepted after rotationService not updated, or two tasks runningdocker service update, then remove the old secret

A final note on scope: a secret in Docker protects against accidental exposure in images, inspect output, and repositories. It does not protect against a host compromise, a root user, or a malicious container with the socket mounted. Treat the file mount as one layer, and put the real boundary where it belongs — in the network policy, the database grants, and the credential's own lifetime.

Try matching browser tools

All tools

Small utilities that fit Docker work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Docker guides

More in Docker

All Docker guides

The guides filed next to this one in Docker, in library order.