patterndockerModerate
Docker secrets provide runtime secret injection without env var exposure
Viewed 0 times
File-based secrets: Compose v2; Encrypted secrets: Docker Swarm
docker secretssecret filerun/secretsenv var exposureswarm secrets_FILE convention
Problem
Database passwords and API keys in environment variables appear in
docker inspect, process lists, and Compose files committed to git. Even with .env files, secrets are too easily exposed.Solution
Use Docker secrets for Swarm or file-based secrets in Compose:
The app reads the password from the file rather than an env var.
services:
app:
image: myapp
secrets:
- db_password
environment:
DB_PASSWORD_FILE: /run/secrets/db_password
secrets:
db_password:
file: ./secrets/db_password.txt # or `external: true` for SwarmThe app reads the password from the file rather than an env var.
Why
Secrets mounted at /run/secrets/ are tmpfs files — they don't appear in env, are not visible in docker inspect environment, and in Swarm mode are encrypted in the Raft log.
Gotchas
- Compose file-based secrets are still stored on disk — they're convenient but not as secure as Swarm encrypted secrets
- App code must support reading secrets from files (the _FILE convention) or you need an entrypoint that reads the file into an env var
- Secrets are available at /run/secrets/<secret-name> inside the container
- Kubernetes uses a different mechanism (Secret resources) — Docker secrets don't transfer
Code Snippets
Entrypoint script to promote _FILE secret to env var
# Read secret file in entrypoint script
#!/bin/sh
if [ -f "$DB_PASSWORD_FILE" ]; then
export DB_PASSWORD=$(cat "$DB_PASSWORD_FILE")
fi
exec "$@"Context
Injecting credentials into containers without exposing them in environment variables
Revisions (0)
No revisions yet.