Skip to main content
Modern application development favors separating configuration from code. By using environment variables—especially within Docker containers—you can adhere to The Twelve-Factor App methodology and deploy more flexibly.

Table of Contents

  1. Why Use Environment Variables?
  2. Step 1: Read Environment Variables Locally
  3. Step 2: Pass Variables into Docker
  4. Docker Commands Reference
  5. Further Reading

Why Use Environment Variables?

Hardcoding configuration values (such as colors, database URLs, or API keys) leads to brittle deployments and requires code changes for every tweak. Environment variables allow you to:
  • Decouple code from deployment details
  • Support multiple environments (dev, staging, prod) without modifying source
  • Secure sensitive data outside of version control
Using environment variables is a best practice for twelve-factor compliant apps.

Step 1: Read Environment Variables Locally

Below is a simple Flask application (app.py) that reads APP_COLOR from the environment, defaulting to "red" if unset.
To test locally:
Visit http://localhost:8080—the page background will reflect your APP_COLOR. If you don’t set APP_COLOR, it gracefully falls back to red.
Never commit sensitive environment variables (like credentials) to your code repository. Consider using a secrets manager for production.

Step 2: Pass Variables into Docker

Once your app is containerized, leverage Docker’s -e flag (or --env-file) to inject runtime configuration.
  1. Build the image
  2. Run with a custom color
  3. Scale with different settings
By externalizing APP_COLOR, you keep one image for all environments—no code changes required.

Docker Commands Reference


Further Reading

Watch Video