How to use Docker secrets for sensitive data

· Category: DevOps & Docker

Short answer

Docker secrets store sensitive data outside images and mount it into containers as read-only files at runtime, reducing the risk of credential leakage through layer history or environment dumps.

Details

In Docker Swarm, create a secret with:

echo "mydbpassword" | docker secret create db_password -

Reference it in a service definition, and the secret appears under /run/secrets/db_password. Even if an attacker gains container access, they cannot read the secret from image layers because it never becomes part of the build. This approach complements broader authentication and authorization policies by limiting what each service can access. If you run outside Swarm, use Compose secrets with file bindings or external secret stores like Vault. Pair secret rotation with secure hashing practices when storing derived credentials.

Tips

  • Mount secrets to tmpfs (/run/secrets) so they never touch persistent disk.
  • Rotate secrets regularly and redeploy services to pick up new values.
  • Avoid printing secret paths in logs or error messages.