Docker Compose Secrets: Keep Credentials Out of Your Code
Docker Compose Secrets inject sensitive data into containers as files at runtime, keeping credentials out of your version-controlled `docker-compose.yml`. Use them for API keys and passwords. The footgun: your app must read from a file, not an env var.
WHY IT EXISTS: Hardcoding secrets like API keys or database passwords directly into docker-compose.yml files or Docker images is a major security risk. It exposes credentials in version control, makes them difficult to rotate, and violates the principle of separating config from code.
THE MENTAL MODEL: Think of secrets as sealed, named envelopes containing sensitive information. You define the envelope's contents in a separate file and just tell Docker Compose which envelopes (secrets) to give to which services. The service receives the envelope at a secure, predictable location inside the container and can open it to read the contents.
HOW IT WORKS: You define a top-level secrets key in your docker-compose.yml. This key lists the secrets you'll use, pointing to external files that contain the actual secret values. Then, within each service definition that needs a secret, you add a secrets block to grant it access. At runtime, Docker mounts each secret as a file into the container's filesystem at /run/secrets/<secret_name>. Your application code then reads the secret from this file.
WHEN TO USE IT: Use secrets for any piece of data you wouldn't want to commit to a public Git repository. This includes database credentials, API keys, private certificates, and other sensitive configuration values. It's the standard mechanism for handling credentials in a Compose environment for local development and simple deployments.
WHEN NOT TO USE IT: Do not use secrets for non-sensitive configuration, like a port number or a public URL; environment variables are better for that. Also, Docker Compose secrets are not a full-blown secrets management solution like HashiCorp Vault or AWS Secrets Manager. Those tools offer advanced features like dynamic secret generation, leasing, and auditing that are necessary for more complex or high-security production environments.
ONE CANONICAL EXAMPLE: A docker-compose.yml file defines a top-level secrets block that declares a secret named db_password and points it to a local file, ./db_password.txt. A postgres service is then granted access to this secret. Inside the service definition, an environment variable POSTGRES_PASSWORD_FILE is set to /run/secrets/db_password. This tells the official Postgres image to read its password from the file that Docker automatically mounted at that path, rather than from a less secure plain-text environment variable.
Read the original → docs.docker.com
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.