Environment Variables
Pass configuration into containers at runtime with the -e flag or an env file.
Syntax
docker run -e KEY=value IMAGEContainers are configured through environment variables, which keep settings separate from your code. This lets the same image behave differently in development and production.
Ways to set variables
-e KEY=value— set one variable inline.--env-file file.env— load many variables from a file.ENVin a Dockerfile — bake in defaults.
Inside the container, the app reads these just like any other environment variable.
Example
# Set variables inline
docker run -d \
-e POSTGRES_USER=admin \
-e POSTGRES_PASSWORD=secret \
-e POSTGRES_DB=shop \
--name db postgres:16
# Or load them from a file
docker run --env-file ./app.env myapp:1.0When to use it
- A team uses environment variables to inject database URLs and API keys into a container at runtime, keeping secrets out of the image.
- A developer uses an env-file to manage a set of 20 local dev variables without typing each -e flag on the command line.
- A CD pipeline passes the TARGET_ENV variable to a container at deploy time to switch between staging and production configurations.
More examples
Pass single environment variable
Injects two environment variables at container start time using the -e flag.
docker run -d \
-e DATABASE_URL=postgres://user:pass@db:5432/mydb \
-e LOG_LEVEL=info \
myapp:latestLoad variables from an env file
Reads all variables from a .env file instead of repeating multiple -e flags.
# .env file:
# DATABASE_URL=postgres://user:pass@db:5432/mydb
# REDIS_URL=redis://cache:6379
# LOG_LEVEL=debug
docker run -d --env-file .env myapp:latestInspect running container env vars
Lists all environment variables currently set in a running container, useful for debugging misconfiguration.
docker inspect myapp --format '{{range .Config.Env}}{{.}}\n{{end}}'
Discussion