docker pass environment variables — --env-file and -e

# Single variable
docker run -e NODE_ENV=production my-image

# Multiple variables
docker run -e NODE_ENV=production -e PORT=3000 my-image

# From a file
docker run --env-file .env my-image

You need to inject configuration (API keys, database URLs, feature flags) into a container at runtime.

.env file format

The file is plain KEY=VALUE, one per line. Comments and blank lines are allowed.

# .env
NODE_ENV=production
DATABASE_URL=postgres://user:pass@db:5432/mydb
SECRET_KEY=s3cr3t
# This line is a comment

Pass a variable from the host environment

If you omit the value, Docker reads it from the host shell:

export MY_TOKEN=abc123
docker run -e MY_TOKEN my-image
# Container sees MY_TOKEN=abc123

Docker Compose env_file

# docker-compose.yml
services:
  app:
    image: my-image
    env_file:
      - .env
      - .env.local

Never bake secrets into images

Avoid ENV SECRET=... in Dockerfiles — it is visible in docker history.

# Use --env-file or Docker secrets instead
docker run --env-file .env.production my-image