Table of Contents
- Why Use Environment Variables?
- Step 1: Read Environment Variables Locally
- Step 2: Pass Variables into Docker
- Docker Commands Reference
- 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.
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.
- Build the image
- Run with a custom color
- Scale with different settings
APP_COLOR, you keep one image for all environments—no code changes required.
Docker Commands Reference
| Command | Purpose | Example |
|---|---|---|
docker build | Build an image from a Dockerfile | docker build -t simple-webapp-color . |
docker run -e VAR=VALUE | Run a container with an environment var | docker run -e APP_COLOR=blue simple-webapp-color |
docker run --env-file ./env.list | Load multiple vars from a file | docker run --env-file ./env.list simple-webapp-color |