Script Valley
Docker: Complete Course
Docker in ProductionLesson 5.4

How to use Docker secrets for sensitive configuration

Docker secrets, tmpfs, /run/secrets, Compose secrets, file-based secrets, environment variable risk, secret rotation

Why Environment Variables Are Not Enough for Secrets

Docker secrets vs environment variable security

Environment variables are visible via docker inspect, in crash logs, and sometimes in application error output. For truly sensitive data โ€” database passwords, API keys, TLS certs โ€” use Docker secrets, which mount as in-memory files accessible only inside the container.

Secrets in Docker Compose (Development)

# Create a secrets file locally
echo "supersecret" > db_password.txt
# docker-compose.yml
services:
  db:
    image: postgres:16
    environment:
      POSTGRES_PASSWORD_FILE: /run/secrets/db_password
    secrets:
      - db_password

secrets:
  db_password:
    file: ./db_password.txt

The secret is mounted at /run/secrets/db_password as a tmpfs file (in-memory, not written to disk). Postgres reads it via the _FILE convention, which many official images support.

Reading a Secret in Application Code

const fs = require('fs');
const password = fs.readFileSync('/run/secrets/db_password', 'utf8').trim();

Never log or print secret values. Rotate secrets by updating the file and redeploying โ€” containers must restart to pick up new secret values.

Up next

Container restart policies and production uptime strategies

Sign in to track progress

How to use Docker secrets for sensitive configuration โ€” Docker in Production โ€” Docker: Complete Course โ€” Script Valley โ€” Script Valley