Module 4 Lesson 5: Environment Variables and Configuration
·DevOps

Module 4 Lesson 5: Environment Variables and Configuration

Master the 12-factor app principle. Learn how to inject configuration into your containers dynamically, keeping your secrets safe and your images portable across environments.

Module 4 Lesson 5: Environment Variables and Configuration

A core rule of professional software (the "Twelve-Factor App") is that you should store your configuration in the Environment, not in the code. Docker makes this incredibly easy.

1. Why Use Environment Variables?

Imagine you have two databases:

  • Dev Database: localhost:5432
  • Prod Database: db.production-server.com:5432

If you "Hardcode" these URLs into your image, you have to build two different images. If you use an Environment Variable (e.g., DB_URL), you build One Image and just tell it which URL to use when you start the container.


2. Injecting Variables in the CLI

Option A: The -e Flag (Single variables)

docker run -e APP_COLOR=blue -e API_KEY=abc12345 my-app

Option B: The --env-file Flag (Many variables)

If you have 50 variables, typing -e 50 times is painful. Put them in a file named .env:

APP_COLOR=red
PORT=8080
DB_URL=postgres://user:pass@mydb:5432

Then run:

docker run --env-file .env my-app

3. Viewing "Inside" the Container

How do you know if the variable actually made it inside?

  1. Inspect: docker inspect <container_id> (Look for the "Config" -> "Env" section).
  2. Print: docker exec <container_id> env (This runs the Linux env command inside the container to list all active variables).

4. Best Practices for Configuration

  1. Defaults in Dockerfile: Use the ENV instruction in your Dockerfile to set "Sane" defaults that work for most developers.
    ENV LOG_LEVEL=info
    
  2. Overriding: Overwrite these defaults in production using the -e flag.
  3. No Secrets in Image: NEVER put passwords or API keys in the Dockerfile ENV instruction. They are visible to anyone who can docker inspect the image.

Exercise: The Rainbow App

  1. Pull the image hashicorp/http-echo. This is a tiny app that echoes back whatever you tell it.
  2. Run it and set an environment variable named TEXT to "Hello from Docker".
    • Hint: docker run -p 5678:5678 -e TEXT="Hello from Docker" hashicorp/http-echo
  3. Visit localhost:5678 in your browser. Do you see the text?
  4. Stop the container and run it again with TEXT="Everything is Awesome". Visit the URL again.
  5. Why is this better than building a new image every time you want to change the text?

Conclusion of Module 4

You are now a Container Manager. You know how to launch containers with specific ports, manage their lifespans, network them together for communication, and save their data using volumes.

Next Module: The power of multi-container apps: Module 5: Docker Compose.

Subscribe to our newsletter

Get the latest posts delivered right to your inbox.

Subscribe on LinkedIn