Learn Docker · 9/12

Docker Environment Variables and Configuration

7 min read

Imagine you are managing a global franchise of coffee shops. The physical layout of the kitchen, the espresso machines, and the tables (your Docker image) are exactly the same everywhere. This consistency makes it easy to build new shops. However, the Wi-Fi password, the manager's name, and the local currency (your configuration) must change depending on whether the shop is in Tokyo, New York, or Paris.

If you permanently painted the Wi-Fi password on the kitchen wall at the factory, you would have to tear down the wall to change it. Instead, you leave a blank picture frame and hand the local manager a sticky note to put in it when the shop opens.

In the Docker world, your application is the coffee shop, and Environment Variables are the sticky notes you hand to the container the moment it starts.


1. Injecting Environment Variables at Runtime 💉

The Problem

Hardcoding configurations inside your source code or your Dockerfile breaks the golden rule of containerization: Build once, run anywhere.

If you hardcode a database URL as localhost:5432 in your application code or Dockerfile, you will have to recompile your entire application and build a brand new Docker image just to point it to your production database at aws-rds.mycompany.com. This wastes time, consumes storage, and guarantees that what you tested in development is structurally different from what runs in production.

The Definition

Environment variables are dynamic key-value pairs maintained by the operating system that affect the behavior of running processes.

The Solution

Docker allows you to inject environment variables into a container at runtime (the exact moment you start the container). This allows the exact same immutable Docker image to connect to a local development database on your laptop, and a secure production database on a cloud server, simply by passing different values when starting it.

How it Works in Practice

When you start a container using the Docker CLI, you use the -e or --env flag to pass key-value pairs.

bash
# Running a Node.js web app and passing a custom port and database URL
docker run -d \
  -p 8080:8080 \
  -e PORT=8080 \
  -e NODE_ENV=production \
  -e DATABASE_URL="postgres://user:[email protected]:5432/db" \
  my-node-app:latest

Under the hood: When Docker starts a container, it tells the Linux kernel to create an isolated process. Docker passes these -e values directly into the execution environment of that specific process. Your Node.js, Python, or Go application simply reads them from the OS memory (e.g., process.env.DATABASE_URL in Node.js) just like it would if it were running natively on your laptop.

ENV in Dockerfile vs. Runtime

You can define default environment variables inside your Dockerfile using the ENV instruction.

dockerfile
# Dockerfile
FROM node:20-alpine
# This sets a default value inside the image
ENV PORT=3000 
EXPOSE $PORT
CMD ["node", "server.js"]

If you run this image normally, the app sees PORT=3000. But if you run it with docker run -e PORT=8080, the runtime flag completely overrides the Dockerfile default.


2. Centralizing Configuration Using .env Files 📝

The Problem

Real-world enterprise applications rarely need just one or two environment variables. They often need twenty: database credentials, AWS S3 bucket names, Stripe API keys, Redis URLs, and logging levels.

Typing a docker run command with 20 different -e flags results in a command that is five miles long. It is exhausting to type, easy to make typos, and impossible to easily share with your coworkers.

The Definition

A .env (dotenv) file is a simple, standardized text file used to store environment variables in a centralized, easily readable format.

The Solution

Instead of chaining endless -e flags, you define all your variables in a .env file and hand that single file to Docker using the --env-file flag. Docker will read the file line-by-line and inject every variable into the container.

How it Works in Practice

First, create a simple text file named .env in your project folder:

text
# .env
NODE_ENV=development
PORT=8080
DATABASE_URL=postgres://devuser:devpass@localhost:5432/devdb
API_KEY=super_secret_dev_key_123
CACHE_TTL=3600

Now, tell Docker to use this file:

bash
docker run -d -p 8080:8080 --env-file .env my-node-app:latest

Industry Standards & Survival Rules

If you remember only one thing from this guide, let it be this: NEVER COMMIT YOUR .env FILE TO VERSION CONTROL (GIT).

If you push your .env file to GitHub, your API keys and database passwords are now public. Somewhere, a security engineer starts crying, and bots will automatically scrape your AWS keys within seconds to mine cryptocurrency on your credit card.

The standard industry workflow:

  1. Add .env to your .gitignore file immediately.
  2. Create a .env.example file that contains the keys but dummy values. This file is committed to Git so your teammates know what variables the app requires.
text
# .env.example (Safe to commit)
NODE_ENV=development
PORT=
DATABASE_URL=
API_KEY=
CACHE_TTL=

When a new developer joins your team, they clone the repo, copy .env.example to .env, and fill in their local credentials.

Using .env with Docker Compose

In modern workflows, you will almost always use Docker Compose. Docker Compose is brilliant because it automatically looks for a .env file in the same directory and uses it without you needing to specify any flags.

yaml
# docker-compose.yml
services:
  web:
    image: my-node-app:latest
    ports:
      - "${PORT}:${PORT}" # Reads PORT from the .env file!
    environment:
      - NODE_ENV=${NODE_ENV}
      - DATABASE_URL=${DATABASE_URL}

3. Managing Secrets and Configs without Hardcoding 🕵️‍♂️

The Problem

Environment variables are great, but they have a fatal security flaw: They are highly visible.

If you inject a production database password via an environment variable, anyone with access to the server can run docker inspect <container_id> and see the password in plain text right in the terminal output. Furthermore, if your application crashes, environment variables are often dumped into error logs, potentially sending your private keys to a third-party logging service like Datadog or Splunk.

The Definition

A "Secret" in software engineering is any piece of sensitive data (passwords, SSH keys, TLS certificates, API tokens) that should strictly be controlled and never exposed in plain text in code, logs, or system configurations.

The Solution

Instead of using environment variables for sensitive data, we use Docker Secrets or file-based configuration. Rather than loading the secret into the system memory (RAM) where the OS can broadcast it, Docker mounts the secret as a read-only text file directly inside the container's file system. Your application reads the file, uses the password, and closes it.

If someone runs docker inspect, they only see a file path, not the password.

How it Works in Practice

While Docker Swarm originally pioneered Docker Secrets, the feature is now fully supported in standard local docker-compose setups, which is what 99% of developers use daily.

Step 1: Create a file containing your secret.
Create a file called db_password.txt and put ONLY your password inside it. (Add this file to .gitignore!).

text
# db_password.txt
Super$ecureP@ssw0rd99!

Step 2: Configure Docker Compose to use it.

yaml
# docker-compose.yml
services:
  database:
    image: postgres:15
    environment:
      # We tell Postgres to look for the password inside a file
      # Many official images support the _FILE suffix exactly for this reason!
      POSTGRES_PASSWORD_FILE: /run/secrets/db_password
    secrets:
      - db_password

secrets:
  db_password:
    file: ./db_password.txt

Under the hood: When you run docker-compose up, Docker takes the contents of db_password.txt from your host machine and creates an in-memory file inside the container exactly at /run/secrets/db_password.

Because it is mounted in an in-memory filesystem (tmpfs), the secret is never written to the container's physical disk. Once the container is stopped, the file disappears into the void.

What if the image doesn't support _FILE environment variables?

Many official Docker images (like Postgres, MySQL, WordPress) are programmed to recognize variables ending in _FILE (e.g., POSTGRES_PASSWORD_FILE).

If you are building your own application, you simply need to write your code to handle it. Instead of blindly reading process.env.DB_PASSWORD, you write a tiny utility that says: "If DB_PASSWORD_FILE exists, read the contents of that file. Otherwise, fall back to DB_PASSWORD."

This file-reading approach is exactly how large-scale enterprise orchestrators like Kubernetes handle secrets, making it a highly transferable and essential industry skill.


📚 References & Further Reading

Challenge

You are a DevOps engineer responsible for deploying a critical application packaged as a Docker image named webapp:2.0. Your task is to correctly configure the application for a production environment using command-line flags and a Docker Compose file, ensuring that configuration is flexible and sensitive data is handled securely.

Task 1: Basic Runtime Configuration
Write the complete docker run command to start the webapp:2.0 image. The container must be named webapp-prod-instance, run in detached mode, and be configured with the following two environment variables directly via command-line flags:

  • APP_ENV should be set to production.
  • API_BASE_URL should be set to https://api.mycorp.com/v1.

Task 2: File-based Configuration
Create the contents of a .env file that will hold the application's non-sensitive configuration. This file should contain the two variables from Task 1, plus a new variable REQUEST_TIMEOUT set to 5000.

Task 3: Secure Deployment with Secrets and .env File
Write a new docker run command to start the webapp:2.0 image. This command must meet the following requirements:

  • Load all configuration variables from the .env file you defined in Task 2.
  • The application's database password, which is stored on the host machine in a file named postgres_pass.txt, must be made available inside the container as a Docker secret. The secret file inside the container should be located at /run/secrets/db_password.
  • The application is designed to read the path to this secret file from an environment variable. Set an environment variable named DB_PASSWORD_FILE to point to the secret's path inside the container.

Task 4: Docker Compose Refactoring
Translate the entire configuration from Task 3 into a docker-compose.yml file.

  • Define a single service named api that uses the webapp:2.0 image.
  • The service must load its environment variables from a file named .env.
  • The service must use a top-level secret named database_password_secret which sources its data from the local host file postgres_pass.txt. This secret should be made available inside the service's container at the path /run/secrets/db_password.
  • The DB_PASSWORD_FILE environment variable must also be set for the service.

Expected result

Task 1 Solution

A docker run command that correctly uses the -d, --name, and two -e flags to configure the container.

shell
docker run -d --name webapp-prod-instance -e APP_ENV=production -e API_BASE_URL=https://api.mycorp.com/v1 webapp:2.0

Task 2 Solution

The plain text content for the .env file, with each key-value pair on a new line.

plaintext
APP_ENV=production
API_BASE_URL=https://api.mycorp.com/v1
REQUEST_TIMEOUT=5000

Task 3 Solution

A docker run command that uses the --env-file flag to load the configuration, the --mount flag to mount the password file as a read-only secret, and an -e flag to set the DB_PASSWORD_FILE variable.

shell
docker run --env-file ./.env --mount type=bind,source=./postgres_pass.txt,target=/run/secrets/db_password,readonly -e DB_PASSWORD_FILE=/run/secrets/db_password webapp:2.0

Note: Using --secret is a newer, more explicit alternative to --mount for this purpose.

Task 4 Solution

A complete docker-compose.yml file defining a service and a top-level secret, linking them correctly.

yaml
version: '3.9'

services:
  api:
    image: webapp:2.0
    env_file:
      - ./.env
    environment:
      - DB_PASSWORD_FILE=/run/secrets/db_password
    secrets:
      - source: database_password_secret
        target: db_password

secrets:
  database_password_secret:
    file: ./postgres_pass.txt
yaml

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.