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?
- Inspect:
docker inspect <container_id>(Look for the "Config" -> "Env" section). - Print:
docker exec <container_id> env(This runs the Linuxenvcommand inside the container to list all active variables).
4. Best Practices for Configuration
- Defaults in Dockerfile: Use the
ENVinstruction in your Dockerfile to set "Sane" defaults that work for most developers.ENV LOG_LEVEL=info - Overriding: Overwrite these defaults in production using the
-eflag. - No Secrets in Image: NEVER put passwords or API keys in the Dockerfile
ENVinstruction. They are visible to anyone who candocker inspectthe image.
Exercise: The Rainbow App
- Pull the image
hashicorp/http-echo. This is a tiny app that echoes back whatever you tell it. - Run it and set an environment variable named
TEXTto"Hello from Docker".- Hint:
docker run -p 5678:5678 -e TEXT="Hello from Docker" hashicorp/http-echo
- Hint:
- Visit
localhost:5678in your browser. Do you see the text? - Stop the container and run it again with
TEXT="Everything is Awesome". Visit the URL again. - 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.