Docker Certified Associate Exam Course

Kubernetes

Environment Variables in Docker Recap

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

Note

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.

import os
from flask import Flask, render_template

app = Flask(__name__)

# Read background color from environment; default to "red"
color = os.environ.get("APP_COLOR", "red")

@app.route("/")
def main():
    print(f"Current color: {color}")
    return render_template("hello.html", color=color)

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=8080)

To test locally:

export APP_COLOR=blue
python app.py

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.

Warning

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
    docker build -t simple-webapp-color .
    
  2. Run with a custom color
    docker run -e APP_COLOR=blue simple-webapp-color
    
  3. Scale with different settings
    docker run -e APP_COLOR=green simple-webapp-color
    docker run -e APP_COLOR=yellow simple-webapp-color
    

By externalizing APP_COLOR, you keep one image for all environments—no code changes required.


Docker Commands Reference

CommandPurposeExample
docker buildBuild an image from a Dockerfiledocker build -t simple-webapp-color .
docker run -e VAR=VALUERun a container with an environment vardocker run -e APP_COLOR=blue simple-webapp-color
docker run --env-file ./env.listLoad multiple vars from a filedocker run --env-file ./env.list simple-webapp-color

Further Reading

Watch Video

Watch video content

Previous
Commands and Arguments in Kubernetes