Docker Compose is a handy tool for running multi-container applications. But when it comes to storing sensitive informationβlike API keys, database passwords, or secret tokensβhardcoding them in your docker-compose.yml
is a big no-no. π§¨
Luckily, Docker Compose supports a secrets feature to keep things safeβeven in local development!
Letβs walk through how to use secrets with local Docker Compose like a pro. πͺ
π§ What Are Docker Secrets?
Docker secrets allow you to store confidential data outside your code. These secrets can be files or values that your services read securely at runtime.
In Swarm mode, secrets are managed by the orchestrator. But in local development (non-Swarm), we can still use secrets with Docker Compose, just in a slightly different way.
ποΈ Folder Structure Example
.
βββ docker-compose.yml
βββ secrets/
β βββ db_password.txt
β βββ api_key.txt
You store your secrets as plain text files in a folder (e.g., secrets/
).
π οΈ Step-by-Step: How to Use Secrets in Local Docker Compose
1. π Create Secret Files
Each secret should be in its own file:
# secrets/db_password.txt
super-secret-password
# secrets/api_key.txt
my-very-secret-api-key
π Keep the
secrets/
folder out of version control by adding it to.gitignore
!
# .gitignore
secrets/
2. π§Ύ Update docker-compose.yml
Hereβs how to use secrets in Compose (v3+):
version: '3.8'
services:
app:
image: your-app-image
build: .
secrets:
- db_password
- api_key
environment:
DB_PASSWORD_FILE: /run/secrets/db_password
API_KEY_FILE: /run/secrets/api_key
db:
image: postgres
environment:
POSTGRES_PASSWORD_FILE: /run/secrets/db_password
secrets:
- db_password
secrets:
db_password:
file: ./secrets/db_password.txt
api_key:
file: ./secrets/api_key.txt
β What Happens Behind the Scenes?
Docker Compose mounts the secret files inside the container at:
/run/secrets/<secret_name>
Your app should read the content of the file, not expect it as an environment variable.
For example, in Node.js you could do:
const fs = require('fs');
const dbPassword = fs.readFileSync('/run/secrets/db_password', 'utf-8').trim();
console.log('DB Password:', dbPassword);
π‘ Pro Tips
- π§ͺ Use
docker-compose down -v
to clear secrets and volumes when stopping services. - π Never log secret values in your console or logs.
- π Use
.env
files only for non-sensitive config in dev.
π§Ή Bonus: Add Some Automation
You can create a script to generate secret files easily:
#!/bin/bash
mkdir -p secrets
echo "super-secret-password" > secrets/db_password.txt
echo "my-very-secret-api-key" > secrets/api_key.txt
echo "β
Secrets created!"
π Wrapping Up
Using secrets in local Docker Compose isnβt just for prosβitβs for anyone who wants to write secure, production-like local setups. With just a few simple steps, you can keep your secrets safe and your app happy.
Remember: Treat your local setup like production and your future self will thank you!
Top comments (0)