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

  1. Define secrets in docker-compose.yml.
  2. Reference them in services under the secrets key.
  3. For Swarm, create secrets with docker secret create.
  4. 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 .env only for non-sensitive configuration; prefer file-based secrets.
  • Rotate secrets by updating the secret file and recreating the container.

Common issues

  • Secrets defined with file are 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.