Course contentsShow
← Software Engineering
Lesson 1436 of 1,93342. Containerization and OrchestrationFree lesson

Environment Variables and Configuration

Master passing configuration to containers via environment variables, .env files, and Docker secrets for sensitive data.

Environment Variables and Configuration

What you'll learn: How to cleanly pass runtime settings and secrets into containers so your applications work anywhere without baking sensitive data into images.

The Core Idea

Containers are meant to be portable and immutable—the same image should run identically in dev, staging, and production. But each environment needs different configuration: database URLs, API keys, feature flags, etc. Environment variables are the primary way to inject this configuration at runtime without rebuilding images.

Think of environment variables like arguments passed to a function. The container image is your function definition—it doesn't change. Environment variables are the inputs that make it behave differently each time you run it.

Three Configuration Approaches

1. Environment Variables
Pass directly when starting a container:

docker run -e DATABASE_URL=postgres://prod-db:5432/myapp myimage

2. .env Files
Store multiple variables in a file and load them together:

docker run --env-file production.env myimage

This keeps long configuration lists organized and prevents exposing values in command history.

3. Docker Secrets (for sensitive data)
Designed for production orchestration systems, secrets are encrypted at rest and only available to authorized containers. They're mounted as files instead of environment variables (which can leak into logs):

docker secret create db_password ./password.txt
docker service create --secret db_password myimage

When to Use What

Use environment variables for non-sensitive config (ports, feature flags). Use .env files to organize multi-variable configurations locally. Use Docker secrets for passwords, tokens, and certificates in production.

Key Takeaway:
Environment variables keep container images generic and portable; use .env files for convenience and Docker secrets to protect sensitive credentials in production.