How to manage secrets in Docker Compose?
· Category: Docker
Short answer
Docker Compose supports secrets via the top-level secrets key, which mounts sensitive files into containers. For Swarm, use docker secret create. For local development, bind mount secret files or use environment variables cautiously.
Steps
- Define secrets in
docker-compose.yml. - Reference them in services under the
secretskey. - For Swarm, create secrets with
docker secret create. - For local dev, use file-based secrets mounted as read-only.
Example
services:
app:
image: myapp
secrets:
- db_password
secrets:
db_password:
file: ./secrets/db_password.txt
Inside the container, the secret is available at /run/secrets/db_password.
Tips
- Never commit secrets to version control.
- Use
.envonly for non-sensitive configuration; prefer file-based secrets. - Rotate secrets by updating the secret file and recreating the container.
Common issues
- Secrets defined with
fileare only available on the local filesystem. - Swarm secrets require Docker Swarm mode and cannot be used in standalone Compose.
- Ensure secret files have restrictive permissions (
chmod 600) before mounting.