Course contentsShow
← Docker, Kubernetes & CI/CD
Lesson 204 of 8023. Docker Orchestration and StorageFree lesson

Managing Configuration via Environment Variables

You will inject runtime configuration settings into containers to allow the same image to behave differently across various deployment environments.

In this lesson, you will learn how to make your containerized applications flexible by injecting configuration settings at runtime using environment variables.

Why Use Environment Variables?

So far, you’ve learned how to connect containers and manage persistent storage. However, if you hardcode settings—like a database URL or an API key—directly into your application code, you’ll be forced to rebuild your Docker image every time you move from a "development" environment to "production."

Environment variables allow you to keep your application code constant while changing its behavior based on where it is running. Think of it like a remote control for your container: you don't rebuild the TV just to change the channel; you send a signal to the hardware telling it what to display.

Applying Configuration in Compose

When working with docker-compose.yml, you can define these variables directly in your service definition. This allows you to override default settings the moment the container starts.

services:
  web-app:
    image: my-app:latest
    environment:
      - DB_HOST=db-service
      - APP_PORT=8080
      - LOG_LEVEL=debug

In this example, the web-app container will look for DB_HOST within its internal environment settings. Because we used Docker’s embedded DNS (which you learned in lesson 201), the application can resolve db-service without knowing its specific IP address.

If you were to deploy this same image to a production environment, you wouldn't change the code; you would simply update the docker-compose.yml file (or provide a separate environment file) to point DB_HOST to your production database server. The container "wakes up," reads the environment variable, and connects to the correct database automatically. This separation of "code" from "configuration" is a fundamental pillar of modern container orchestration, ensuring that your application remains portable and secure across different infrastructure setups.

Key Takeaway: Use environment variables to inject runtime configuration, allowing a single, immutable container image to adapt to any environment without requiring code changes.