Back to course

Lesson 23: Handling Environment Variables and Secrets

Docker Zero to Hero: The Complete Containerization Course for Beginners

Lesson 23: Handling Environment Variables and Secrets

Applications rely on configuration, often passed via environment variables (DB credentials, API keys). Docker provides several ways to manage these.

1. Defining Variables in Dockerfile (ENV)

Use ENV to set static environment variables inside the image.

dockerfile ENV APP_VERSION=1.0.0 ENV PORT=8080

2. Passing Variables at Runtime (docker run)

For sensitive or dynamic data (like passwords), never hardcode them in the Dockerfile. Pass them at runtime using the -e flag.

bash docker run -d \n -e DB_USER=production_user \n -e DB_PASS=supersecret! \n my-app:latest

3. Using an Environment File (--env-file)

For many variables, listing them all with -e is tedious. You can use an .env file.

prod.env file content:

ini DB_USER=prod_user API_KEY=xyz123abc

Runtime command:

bash docker run -d --env-file ./prod.env my-app:latest

4. Compose Environment Management

Docker Compose simplifies this using the environment: block (Lesson 18) or external .env files.

If you have an external .env file in the same directory as your compose.yml, Compose automatically loads it and substitutes variables defined in your compose.yml:

compose.yml snippet:

yaml services: web: image: my-app:latest environment: DB_USER: ${DB_USER} # Or hardcode a variable only for this service LOG_LEVEL: info

Security Note on Secrets: For true production security (i.e., when using Swarm or Kubernetes), environment variables are not considered fully secure. Docker provides dedicated Secrets management (encrypted storage), which we will briefly mention in later orchestration lessons.