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
.envfile 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
| Method | Command or File |
|---|---|
CLI with -e | docker run -e VAR=value image |
.env file | docker run --env-file .env image |
Dockerfile ENV | ENV VAR=value |
| Docker Compose | environment: or env_file: |
Environment variables offer a flexible, secure way to configure containers. Choose the method that fits your workflow best.