How Do I Pass Environment Variables to Docker Containers?

Environment variables are a convenient and secure way to configure applications without hardcoding values. Docker makes it easy to pass these variables into containers at runtime.

In this blog, we’ll explore multiple ways to pass environment variables into Docker containers effectively.


πŸ“¦ Why Use Environment Variables in Docker?

Using environment variables allows you to:

  • Configure containers without modifying code
  • Easily switch environments (e.g., dev, staging, production)
  • Securely manage sensitive values like API keys and credentials

πŸ”§ Method 1: Use the -e Flag with docker run

You can pass environment variables directly using the -e or --env option:

docker run -e MY_VAR=value my-image

Multiple variables? No problem:

docker run -e VAR1=value1 -e VAR2=value2 my-image

πŸ“„ Method 2: Use an .env File

An .env file is a simple key-value file that Docker can read:

.env

DB_HOST=localhost
DB_USER=admin
DB_PASS=secret

Then pass it with:

docker run --env-file .env my-image

βœ… Great for managing multiple variables in one place.


🧩 Method 3: Define Environment Variables in Dockerfile

You can set default values using the ENV instruction in your Dockerfile:

ENV PORT=3000
ENV NODE_ENV=production

These variables are baked into the image, but can still be overridden at runtime.


πŸ› οΈ Method 4: Using Docker Compose

In docker-compose.yml, environment variables can be defined inline or from an external .env file:

services:
  web:
    image: my-image
    environment:
      - DB_HOST=localhost
      - DB_USER=admin

Or load from .env automatically:

version: '3'
services:
  web:
    image: my-image
    env_file:
      - .env

πŸ“ Docker Compose automatically loads a .env file in the same directory.


πŸ” Pro Tip: Keep Secrets Secure

Avoid hardcoding secrets in the Dockerfile or docker-compose.yml. Use environment variables passed at runtime or integrate Docker secrets for production use.


βœ… Summary

MethodCommand or File
CLI with -edocker run -e VAR=value image
.env filedocker run --env-file .env image
Dockerfile ENVENV VAR=value
Docker Composeenvironment: or env_file:

Environment variables offer a flexible, secure way to configure containers. Choose the method that fits your workflow best.

Sharing Is Caring:

Leave a Comment