Module 7 Lesson 4: Docker Secrets vs. Env Vars
Protect your crown jewels. Learn the technical difference between environment variables and Docker Secrets, and why one is a security risk for production databases.
Module 7 Lesson 4: Docker Secrets vs. Env Vars
In Module 4, we learned how to use Environment Variables (-e) to pass configuration. While convenient, they are inherently insecure for passwords and API keys.
1. Why Environment Variables are "Leaky"
If you pass a password via an environment variable:
docker inspect: Anyone with access to the Docker CLI can see the password in plain text.- Logs: If your app crashes and prints its environment, the password is now in your log files (ElasticSearch, Splunk).
- Child Processes: Every process started by your app can see the password.
2. What are Docker Secrets?
Docker Secrets are a more secure way to handle sensitive data.
- Encrypted in Transit: They are sent to the container over an encrypted network.
- In-Memory Only: Inside the container, the secret is mounted as a file in a special folder (
/run/secrets/). It is never written to disk and never sits in the environment variables.
3. Using Secrets in Docker Compose
Secrets were originally for Docker Swarm, but you can use them in modern docker-compose too.
services:
db:
image: postgres
secrets:
- db_password # The container can now see /run/secrets/db_password
secrets:
db_password:
file: ./my_password.txt # The password is read from this file on your laptop
How the App uses it:
Instead of reading os.env('PASSWORD'), your app reads the contents of the file /run/secrets/db_password.
4. When to Use Which?
| Feature | Environment Variables | Docker Secrets |
|---|---|---|
| Good for... | Public Config (Port, Log Level) | Private Config (API Key, DB Pass) |
| Visibility | High (docker inspect) | Low (No metadata visibility) |
| Storage | Plain text on host | Encrypted (Swarm) / File-based |
| Complexity | Very Easy | Requires app support (reading files) |
Exercise: The Secret Swap
- Create a file named
secret_key.txtwith the text"SUPER_SALT_123". - Write a
docker-compose.ymlthat adds this file as a secret to arediscontainer. - Run
docker-compose up -d. - Use
docker execto "Look" for the secret:cat /run/secrets/secret_key. Did you find it? - Now run
docker inspect. Can you find the string"SUPER_SALT_123"anywhere in the metadata? - Why is this method safer for a team working with a shared Git repository? (Hint: check what you would exclude in
.gitignore).
Conclusion of Module 7
You have now mastered Docker Security. You know how to scan for bugs, run as a safe user, and protect your passwords using Secrets. These habits are what distinguish a "Script Kiddie" from a "Senior DevOps Engineer."
Next Module: The local development loop: Module 8: Docker for Local Development.