- English
- English
Appearance
Appearance
An environment variable is a configuration value available to an application process while a container is running. Examples include a database password, database name, service URL, or application mode.
Environment variables let you use one image in several environments without changing or rebuilding the image.
Command format:
docker run -d --name <container-name> -e <VARIABLE_NAME>=<value> <image:tag>Example:
docker run -d --name db \
-e POSTGRES_PASSWORD=secret \
-e POSTGRES_DB=app \
postgres:16The -e option adds an environment variable to the container. To add several variables, use -e several times.
The official PostgreSQL image reads POSTGRES_PASSWORD and POSTGRES_DB on its first start. Each image has its own rules about which variable names it supports. Read the documentation for the image you use.
To see the environment variables available inside the db container, make sure the container is still running. This command can help with local debugging:
docker exec db envThis output may contain passwords or other secrets. Do not share it or use this method to inspect secrets in a production environment.
Do not put a password or secret in a Dockerfile:
ENV PASSWORD=secretA Dockerfile is part of the source code and image. A secret written there can end up in the repository, image history, and containers created from the image.
For local development, use environment variables with docker run or use a .env file with Docker Compose. In production, use the secret manager provided by your platform.
In Docker Compose, environment variables are written under environment:
services:
db:
image: postgres:16
environment:
POSTGRES_PASSWORD: secret
POSTGRES_DB: appValues can also come from a .env file. When Compose reads compose.yaml, it replaces ${POSTGRES_PASSWORD} with the POSTGRES_PASSWORD value from that file:
POSTGRES_PASSWORD=secretservices:
db:
image: postgres:16
environment:
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}Add a .env file containing secrets to .gitignore. Never commit production secrets to Git.
The next lesson uses these environment variable concepts with Docker Compose.