9.2.5 Compose Secrets
A focused guide to Compose Secrets, connecting core concepts with practical Docker and container operations.
Compose secrets provide a mechanism specifically intended for sensitive data — passwords, API keys, certificates — distinct from the general-purpose configs mechanism, with handling designed to reduce the exposure of this sensitive content compared to ordinary environment variables or configuration files.
Declaring and Using a Secret
A secret is declared at the top level, referencing a source for its sensitive content, then attached to whichever services need access to it.
services:
api:
secrets:
- db-password
secrets:
db-password:
file: ./secrets/db-password.txt
How a Secret Becomes Accessible Inside a Container
Rather than appearing as an environment variable, a secret's content is made available as a file, typically under a dedicated /run/secrets/ directory inside the container.
docker compose exec api cat /run/secrets/db-password
An application reads its sensitive value directly from this file path, rather than from an environment variable that might be more broadly visible through process inspection or accidental logging.
Why Secrets Are Preferred Over Environment Variables for Sensitive Data
Environment variables can be inadvertently exposed through process listings, crash dumps, or accidental logging in ways a dedicated secrets file is somewhat more protected against, making secrets the more appropriate mechanism specifically for genuinely sensitive values.
services:
api:
environment:
- DB_PASSWORD=supersecret
services:
api:
secrets:
- db-password
secrets:
db-password:
file: ./secrets/db-password.txt
The second approach reduces this particular category of accidental exposure risk compared to the first.
Excluding Secret Source Files From Version Control
The actual file backing a secret should never be committed to version control, since doing so would defeat the purpose of treating its content as sensitive in the first place.
secrets/
Why Compose Secrets Matter
Using the dedicated secrets mechanism for genuinely sensitive data provides a meaningfully more careful handling approach than ordinary environment variables or configuration files, reducing the risk of this sensitive content being inadvertently exposed.