Environment Variables

Environment Variables and Container Configuration

Images are generic; you configure each container at start-up through environment variables. The PostgreSQL 1,289 image reads POSTGRES_PASSWORD (required), POSTGRES_USER and POSTGRES_DB when it first initializes its data directory; without the password it exits with "Error: Database is uninitialized and superuser password is not specified."

BookNest's API connects as user booknest to database booknest. An env file holds one NAME=value per line, and individual -e flags add to it or override it:

Configuring the database from an env fileShell
printf '%s\n' POSTGRES_USER=booknest POSTGRES_PASSWORD=booknest POSTGRES_DB=booknest > booknest.env
docker rm -f -v l3-postgres
docker run -d --name l3-postgres --env-file booknest.env -e TZ=UTC postgres:18
sleep 5   # first start: initdb runs, then the real server starts
docker exec l3-postgres psql -U booknest -Atc 'SELECT current_user, current_database()'
docker inspect l3-postgres --format '{{range .Config.Env}}{{println .}}{{end}}' | head -4
Output
l3-postgres
fb05f72243d64fc123fe3ff13c002f10b8735e6d097489c7a640b04a4c028914
booknest|booknest
POSTGRES_USER=booknest
POSTGRES_PASSWORD=booknest
POSTGRES_DB=booknest
TZ=UTC

A running container's environment cannot change, so you replace the container (-v also deletes its data volume, see Container Lifecycle). The last command shows the weakness: anyone who can run docker inspect reads the password. Keep env files out of Git 1,932 (BookNest's .gitignore excludes only .env), and for real secrets use the image's POSTGRES_PASSWORD_FILE with Compose 514 secrets (Secrets and Configs in Compose). These variables act only on first start; changing them later against existing data does not change the stored password.