Docker Compose Secrets: Production Hardening Guide
Article Details
Category
DevOpsStoring sensitive production credentials—such as database passwords, API tokens, Stripe keys, and TLS private keys—in environment variables (environment: or .env files) inside Docker Compose is one of the most widespread container anti-patterns. While convenient for local development, environment variables expose secrets to significant operational leakage.
Any engineer with read-only Docker socket access can run docker inspect <container> and view all plaintext secrets in JSON output. Application crash reports and Application Performance Monitoring (APM) agents routinely dump the host environment into logs during uncaught exceptions. Child processes inherit environment variables by default, and inspecting /proc/<pid>/environ exposes credentials to any compromised process inside the container namespace.
This guide provides a practical production hardening runbook. You will learn how to transition from insecure environment variables to native Docker Compose secrets, mount credentials into memory-backed tmpfs directories (/run/secrets/), configure standard _FILE entrypoint conventions for databases, and securely rotate secrets without downtime.
If you are locking down container infrastructure at the host operating system level, pair this guide with our production walkthrough on Docker rootless mode hardening.
Threat Model: Why Environment Variables Fail Container Security
Before deploying Compose secrets, consider where environment variables leak across the container lifecycle.
Figure 1: Comparison between insecure environment variable leakage and memory-mounted Docker secrets.
When an environment variable is injected into a container:
docker inspectExposure: The Docker daemon persists container environment configurations in/var/lib/docker/containers/<id>/config.v2.json. Runningdocker inspectoutputs passwords in plaintext, bypassing application-level logging controls.- Crash Dump Exfiltration: If an unhandled exception triggers a crash in Node.js, Python, or Go, error trackers like Sentry, Datadog, or Rollbar often serialize
process.envoros.environinto crash payloads sent to external telemetry endpoints. - Child Process Inheritance: Any sub-process spawned via
exec(),fork(), or third-party CLI tools inherits the entire parent environment table. - Process Table Snooping: Within the container (or from the host if PID namespaces are shared), credentials can be extracted directly via
/proc/<pid>/environ.
Docker Compose Secrets solve this problem by decoupling credentials from the process environment table. Secrets are presented as discrete files mounted into /run/secrets/<secret_name>, backed by an in-memory temporary filesystem (tmpfs). They never touch disk within the container filesystem layer, are omitted from docker inspect, and are accessible only to authorized processes with filesystem read permissions.
Implementation: Native Docker Compose Secrets
Docker Compose supports file-based secrets natively in both Compose Specification (Compose V2) and Docker Swarm mode.
+-------------------------------------------------------------+
| SECRET HARDENING PIPELINE |
| |
| 1. Generate cryptographically random secret files |
| 2. Set strict host permissions (chmod 400, chown root) |
| 3. Declare top-level 'secrets:' block in compose.yaml |
| 4. Scope secret access specifically to target containers |
| 5. Configure applications via _FILE entrypoint pattern |
+-------------------------------------------------------------+
Step 1: Create Host Secret Files
Store your secrets in a dedicated directory outside of your source code repository (e.g., /etc/compose-secrets/ or a gitignored secrets/ directory):
mkdir -p ./secrets
chmod 700 ./secrets
# Generate a strong 32-character random database password
openssl rand -base64 32 | tr -d '\n' > ./secrets/db_password.txt
openssl rand -base64 32 | tr -d '\n' > ./secrets/app_secret_key.txt
# Lock down file permissions strictly to root / deployment user
chmod 400 ./secrets/*.txt
Verify that .gitignore ignores secret files:
# .gitignore
secrets/
*.txt
*.key
.env
Step 2: Configure compose.yaml with Secrets
Create your production compose.yaml declaring top-level secret definitions and attaching them to specific service workloads:
services:
db:
image: postgres:16-alpine
restart: unless-stopped
environment:
POSTGRES_USER: app_admin
POSTGRES_DB: production_db
# Use the official _FILE convention supported by official images
POSTGRES_PASSWORD_FILE: /run/secrets/db_password
secrets:
- db_password
volumes:
- db_data:/var/lib/postgresql/data
networks:
- internal_net
api:
build:
context: .
dockerfile: Dockerfile
restart: unless-stopped
ports:
- "8080:8080"
environment:
NODE_ENV: production
DB_HOST: db
DB_USER: app_admin
DB_NAME: production_db
# Inform your application where to locate secret mounts
DB_PASSWORD_FILE: /run/secrets/db_password
APP_SECRET_FILE: /run/secrets/app_secret_key
secrets:
- db_password
- app_secret_key
depends_on:
- db
networks:
- internal_net
secrets:
db_password:
file: ./secrets/db_password.txt
app_secret_key:
file: ./secrets/app_secret_key.txt
volumes:
db_data:
networks:
internal_net:
internal: true
Step 3: Verify Secret Isolation
Deploy the stack:
docker compose up -d
Now verify that docker inspect does not leak the password:
docker inspect $(docker compose ps -q db) | grep -i "POSTGRES_PASSWORD"
Output:
"POSTGRES_PASSWORD_FILE=/run/secrets/db_password"
The password is not present in the inspect payload. Next, verify that the file exists inside the container’s /run/secrets/ path:
docker compose exec db cat /run/secrets/db_password
The secret is mounted as a read-only file with mode 0444.
Application Code: Consuming File Secrets
Many official Docker images (PostgreSQL, MySQL, Redis, MariaDB) natively support the _FILE convention out of the box. However, your internal application services (Node.js, Python, Go, Rust) must be written to read credentials from the filesystem if present.
Node.js / TypeScript Example
Implement a reusable secret-loader helper that falls back to standard environment variables during local development:
import fs from 'node:fs';
export function getSecret(envKey: string, fileEnvKey: string): string {
// 1. Check if a _FILE path is specified
const filePath = process.env[fileEnvKey];
if (filePath && fs.existsSync(filePath)) {
return fs.readFileSync(filePath, 'utf8').trim();
}
// 2. Fall back to standard environment variable (for local dev)
const directValue = process.env[envKey];
if (directValue) {
return directValue;
}
throw new Error(`Missing required secret: Neither ${fileEnvKey} nor ${envKey} is defined.`);
}
// Usage in database pool configuration:
const dbPassword = getSecret('DB_PASSWORD', 'DB_PASSWORD_FILE');
Python Example
import os
from pathlib import Path
def get_secret(env_var: str, file_env_var: str, default: str = None) -> str:
file_path = os.getenv(file_env_var)
if file_path:
path = Path(file_path)
if path.is_file():
return path.read_text(encoding="utf-8").strip()
direct_val = os.getenv(env_var)
if direct_val:
return direct_val
if default is not None:
return default
raise ValueError(f"Secret not found for {env_var} or {file_env_var}")
# Usage:
db_password = get_secret("DB_PASSWORD", "DB_PASSWORD_FILE")
Go (Golang) Example
package main
import (
"fmt"
"os"
"strings"
)
// GetSecret reads from a mounted secret file or falls back to an environment variable.
func GetSecret(envKey, fileEnvKey string) (string, error) {
if filePath := os.Getenv(fileEnvKey); filePath != "" {
data, err := os.ReadFile(filePath)
if err == nil {
return strings.TrimSpace(string(data)), nil
}
}
if val := os.Getenv(envKey); val != "" {
return val, nil
}
return "", fmt.Errorf("required secret missing: neither %s nor %s is set", fileEnvKey, envKey)
}
Generic Shell Entrypoint Wrapper for Legacy Images
If you are running legacy third-party containers (like custom Java jars or legacy PHP apps) that strictly expect environment variables and cannot be rewritten to read /run/secrets/, use an entrypoint script to read the file into memory immediately before executing the binary. This keeps the secret out of docker inspect while satisfying legacy software:
#!/usr/bin/env sh
set -eu
# If secret file exists, read into process environment before exec
if [ -f "/run/secrets/db_password" ]; then
DB_PASSWORD="$(cat /run/secrets/db_password)"
export DB_PASSWORD
fi
# Execute main process as PID 1
exec "$@"
In your Dockerfile:
COPY entrypoint.sh /usr/local/bin/entrypoint.sh
RUN chmod +x /usr/local/bin/entrypoint.sh
ENTRYPOINT ["/usr/local/bin/entrypoint.sh"]
CMD ["node", "server.js"]
Zero-Downtime Secret Rotation Runbook
Rotating compromised or scheduled secrets without restarting dependent workloads requires a structured procedure.
+-------------------------------------------------------------+
| ZERO-DOWNTIME SECRET ROTATION WORKFLOW |
| |
| 1. Provision new database user credentials in target DB |
| 2. Create new versioned secret file (db_password_v2.txt) |
| 3. Add secret to compose.yaml under a versioned alias |
| 4. Execute rolling update of API worker containers |
| 5. Revoke old credentials in the database |
+-------------------------------------------------------------+
Step 1: Update the Secret Definitions in compose.yaml
Rather than overwriting existing secret files in place (which can cause temporary inconsistencies across containers during reboots), treat secrets as immutable artifacts with explicit versioning:
services:
api:
image: my-app:latest
environment:
DB_PASSWORD_FILE: /run/secrets/db_password_v2
secrets:
- source: db_password_v2
target: db_password_v2
secrets:
db_password_v1:
file: ./secrets/db_password_202611.txt
db_password_v2:
file: ./secrets/db_password_202612.txt
Step 2: Trigger a Rolling Update
Execute a rolling recreate of the API service:
docker compose up -d --no-deps --build api
The Docker engine creates new container instances with the new secret mount, drains old connections, and switches traffic without dropping user requests.
Production Security Hardening Matrix
| Security Control | Implementation | Threat Mitigated |
|---|---|---|
| Mount Permissions | secrets.target: /run/secrets/app.key, mode: 0400 | Limits read access to container root / UID 0 |
| Non-Root Containers | Set uid: "10001", gid: "10001" in secret spec | Allows non-root containers to read secrets without privilege escalation |
| Ephemeral Memory | Backed by tmpfs automatically by Compose | Prevents unencrypted keys being written to host swap or backing SSDs |
| Least Privilege Scope | Define secret attachments only on specific services | Prevents worker containers from accessing database master keys |
Specifying UID/GID and File Permissions in Compose
To deliver secrets securely to containers running as unprivileged users (e.g., nobody or a non-root app user):
services:
api:
image: my-app:non-root
user: "10001:10001"
secrets:
- source: app_secret_key
target: /run/secrets/app_secret_key
uid: "10001"
gid: "10001"
mode: 0400
secrets:
app_secret_key:
file: ./secrets/app_secret_key.txt
Verification & Audit Checklist
- All database and third-party API credentials are moved out of
.envfiles andenvironment:arrays. - No secrets appear when executing
docker inspect <container>. - Secret files on the host filesystem have permissions set to
0400owned by the deploying user. - Application entrypoints read credentials from files specified by
_FILEenvironment pointers. - Production
.gitignoreexplicitly excludes all.txt,.key, andsecrets/subdirectories.
Related Runbooks
Implementation Checklist
- Replicate the steps in a controlled lab before production changes.
- Document configs, versions, and rollback steps.
- Set monitoring + alerts for the components you changed.
- Review access permissions and least-privilege policies.
Official References
Need a Hand?
If you want this implemented safely in production, I can help with assessment, execution, and hardening.
Contact MeDeploy on Cloud Infrastructure with $200 Free Credit
Spin up high-performance SSD cloud Droplets, managed Kubernetes, and databases in seconds. Test your containers and production workloads with $200 in free credits.
Transparency: We independently test and operate all recommended infrastructure. If you use our partner links, you receive free promotional credits and support our testing lab at zero extra cost to you.
Weekly Production DevOps Runbooks
Join 1,000+ infrastructure engineers receiving real-world Linux troubleshooting, Proxmox clustering setups, and Docker optimization runbooks every Tuesday. Zero spam, unsubscribe anytime.
About the Author
Kamandanu Wijaya
IT Infrastructure & Network Administrator
Infrastructure & network administrator with 15+ years of enterprise experience, focused on stability, security, and automation.
Certifications: Google IT Support, Cisco Networking Academy, DevOps.
Linux XFS Corruption: Safe Repair Guide Without Data Loss
Next →Cloudflare Tunnel RDP: Secure Remote Desktop Access Guide
Need IT Solutions?
DoWithSudo is ready to help setup servers, VPS, and your security systems.
Contact Us