Skip to content

Environment variables and secrets in Compose

Select an icon to see what it is.

Step 6 of 6

What a file secret does not do

The secret is still a plain file on the host, so protect it with file permissions and keep it out of git. Compose does not encrypt it. Swarm secrets are different: they are stored encrypted in the cluster and mounted from memory.

PrevNext

Summary

host file: readable by anyone who can read the project directory
container: read-only file at /run/secrets/<name>
Swarm secrets: encrypted in the cluster, mounted from memory

Try it yourself

Compare an environment variable with a file secret using docker inspect.

$ printf 'example' > db_password.txt
$ cat > compose.yaml <<'EOF' name: shop services: api: image: traefik/whoami command: ["--port", "3000"] environment: DB_HOST: db DB_PASSWORD: ${DB_PASSWORD} networks: default: ipv4_address: 172.18.0.3 db: image: postgres:17 environment: POSTGRES_PASSWORD_FILE: /run/secrets/db_password secrets: - db_password networks: default: ipv4_address: 172.18.0.4 secrets: db_password: file: ./db_password.txt networks: default: name: shop-net ipam: config: - subnet: 172.18.0.0/16 EOF
$ DB_PASSWORD=example docker compose up -d
$ docker inspect --format '{{json .Config.Env}}' shop-api-1
$ docker inspect --format '{{json .Config.Env}}' shop-db-1
$ docker exec shop-db-1 cat /run/secrets/db_password
$ docker compose down

Quiz

1. Who replaces ${DB_PASSWORD} in compose.yaml?
2. Why are secrets files better than environment variables for passwords?
3. Where does a Compose file secret appear in the container?