9.2.5.2 Compose Secret Mounts
A focused guide to Compose Secret Mounts, connecting core concepts with practical Docker and container operations.
Compose secret mounts describe exactly how a declared secret becomes accessible inside a service's container — mounted as a file under a dedicated, typically tmpfs-backed directory — rather than appearing as an environment variable, reflecting the more careful handling intended for genuinely sensitive content.
Where Secrets Are Mounted by Default
Without further customization, a secret's content appears as a file named after the secret, located under /run/secrets/ inside the container.
services:
api:
secrets:
- db-password
secrets:
db-password:
file: ./secrets/db-password.txt
docker compose exec api ls /run/secrets/
docker compose exec api cat /run/secrets/db-password
Why This Mount Location and Mechanism Matters
Mounting secret content as a file, under a directory not typically scanned or logged by general application tooling, reduces the chance of this sensitive content being inadvertently exposed compared to broader mechanisms like environment variables.
with open('/run/secrets/db-password') as f:
db_password = f.read().strip()
An application reads its sensitive value directly from this file, treating the secret mount as the authoritative source for this particular piece of configuration.
Customizing the Mounted Filename
The filename a secret's content appears under can be customized, distinct from the secret's own declared name, useful for matching whatever filename an application specifically expects.
services:
api:
secrets:
- source: db-password
target: postgres_password
Why Compose Secret Mounts Matter
Understanding exactly how and where secret content becomes accessible inside a container is essential both for correctly building an application to read from this location and for appreciating the specific handling advantages this mechanism provides over less careful alternatives like plain environment variables.