Module 7 Lesson 4: Docker Secrets vs. Env Vars
·DevOps

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:

  1. docker inspect: Anyone with access to the Docker CLI can see the password in plain text.
  2. Logs: If your app crashes and prints its environment, the password is now in your log files (ElasticSearch, Splunk).
  3. 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?

FeatureEnvironment VariablesDocker Secrets
Good for...Public Config (Port, Log Level)Private Config (API Key, DB Pass)
VisibilityHigh (docker inspect)Low (No metadata visibility)
StoragePlain text on hostEncrypted (Swarm) / File-based
ComplexityVery EasyRequires app support (reading files)

Exercise: The Secret Swap

  1. Create a file named secret_key.txt with the text "SUPER_SALT_123".
  2. Write a docker-compose.yml that adds this file as a secret to a redis container.
  3. Run docker-compose up -d.
  4. Use docker exec to "Look" for the secret: cat /run/secrets/secret_key. Did you find it?
  5. Now run docker inspect. Can you find the string "SUPER_SALT_123" anywhere in the metadata?
  6. 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.

Subscribe to our newsletter

Get the latest posts delivered right to your inbox.

Subscribe on LinkedIn