Lesson 15 / 25

Secrets as Files

Keep passwords out of environment variables.

secrets: and *_FILE variables

Compose secrets are declared at the top level (from a file or an environment variable) and granted to specific services, which see them as files under /run/secrets/<name>. Many official images accept *_FILE variables (for example POSTGRES_PASSWORD_FILE) that read the value from such a file. This keeps secrets out of docker inspect output and process environments. Keep the secret files out of git (add them to .gitignore).

The db secret in the resolved configuration, run

I ran this with Docker Compose v2.38.1 and jq in the demo "shop" project. docker compose config parses, interpolates, merges and validates the files without starting containers; the Docker daemon was not running, so nothing was started. The db service receives db_password mounted at /run/secrets/db_password, and the image reads it through POSTGRES_PASSWORD_FILE instead of a plain environment variable.

docker compose config --format json | jq -c ".services.db.secrets, .services.db.environment.POSTGRES_PASSWORD_FILE"

Output:

[{"source":"db_password","target":"/run/secrets/db_password"}]
"/run/secrets/db_password"

Git-ignore secret files

Add the secrets folder to .gitignore and provide a script or instructions to create it locally.

Quick check: Where does a service see a Compose secret?

  • As a file under /run/secrets/
  • As a command-line argument
  • In the image layers
  • In the Compose project name
Answer

As a file under /run/secrets/ — Files are safer than environment variables.