Skip to content

Environment Variable ​

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.

Provide an environment variable when starting a container ​

Command format:

sh
docker run -d --name <container-name> -e <VARIABLE_NAME>=<value> <image:tag>

Example:

sh
docker run -d --name db \
  -e POSTGRES_PASSWORD=secret \
  -e POSTGRES_DB=app \
  postgres:16

The -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:

sh
docker exec db env

This output may contain passwords or other secrets. Do not share it or use this method to inspect secrets in a production environment.

Do not store secrets in a Dockerfile ​

Do not put a password or secret in a Dockerfile:

dockerfile
ENV PASSWORD=secret

A 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.

Environment variables in Compose ​

In Docker Compose, environment variables are written under environment:

yaml
services:
  db:
    image: postgres:16
    environment:
      POSTGRES_PASSWORD: secret
      POSTGRES_DB: app

Values can also come from a .env file. When Compose reads compose.yaml, it replaces ${POSTGRES_PASSWORD} with the POSTGRES_PASSWORD value from that file:

dotenv
POSTGRES_PASSWORD=secret
yaml
services:
  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.