Setting Environment Variables with -e Flag

Learn how to pass environment variables to Docker containers using the -e flag. Understand variable precedence, common patterns for configuration, and security best practices for secrets.

Environment & Config

Detailed Explanation

Configuring Containers with Environment Variables

Environment variables are the standard way to configure Docker containers at runtime. The -e (or --env) flag passes key-value pairs to the container:

docker run -d \
  -e NODE_ENV=production \
  -e PORT=3000 \
  -e DATABASE_URL=postgres://user:pass@db:5432/myapp \
  my-node-app

Inside the container, these variables are accessible through the standard environment variable mechanisms (process.env in Node.js, os.environ in Python, etc.).

Syntax Variations

# Explicit key=value
-e MY_VAR=my_value

# Pass host environment variable (same name)
-e MY_VAR                  # Passes the host's MY_VAR value

# Empty value
-e MY_VAR=                 # Sets MY_VAR to empty string

# Quotes for values with spaces
-e "MY_VAR=hello world"

Passing Host Variables Through

If you omit the value, Docker passes the variable from the host environment:

export API_KEY=abc123
docker run -e API_KEY my-app  # Container receives API_KEY=abc123

This is useful for secrets that should not appear in command history or scripts.

Multiple Environment Variables

Most real applications need many variables. Each requires its own -e flag:

docker run -d \
  -e DB_HOST=db.example.com \
  -e DB_PORT=5432 \
  -e DB_USER=admin \
  -e DB_PASS=secret \
  -e DB_NAME=myapp \
  -e REDIS_URL=redis://cache:6379 \
  -e LOG_LEVEL=info \
  -e CORS_ORIGIN=https://example.com \
  my-api

For many variables, consider using an env file instead (see the env-file example).

Common Environment Variable Patterns

Pattern Example
Database connection DATABASE_URL=postgres://...
Feature flags ENABLE_CACHE=true
Runtime mode NODE_ENV=production
Service discovery API_HOST=api.internal
Logging LOG_LEVEL=debug

Security Considerations

  • Command history: Variables set with -e appear in docker inspect output and shell history. Use env files or Docker secrets for sensitive data.
  • Image layers: Never bake secrets into Docker images with ENV in a Dockerfile. Use runtime injection instead.
  • Logging: Ensure your application does not log sensitive environment variables at startup.
  • Principle of least privilege: Only pass the variables a container actually needs.

Use Case

Deploying a Node.js API server that requires database credentials, API keys, and feature flags to be configured differently across development, staging, and production environments.

Try It — Docker Run Command Builder

Open full tool