Compose Environment and Volumes
Compose sets environment variables and mounts volumes from the file. The environment block sets variables per service, a .env file holds them in one place, and a named volume keeps data past a restart.
Variables in the file
The environment block sets the database password.
services:
db:
image: postgres:16-alpine
environment:
POSTGRES_PASSWORD: secret
volumes:
- pgdata:/var/lib/postgresql/data
volumes:
pgdata:Variables from .env
The .env file holds the value, and the file reads it.
POSTGRES_PASSWORD=secretExample
docker compose -p g6proj up -d >/dev/null
docker compose -p g6proj exec db psql -U postgres -c "SELECT 1;"
docker compose -p g6proj downKey points
- environment: the block that sets variables for one service.
- .env: a file of KEY=value lines that Compose reads at start.
- Use ${NAME} in the file to read a value from the .env file.
- volumes: the block that mounts a named volume into a service.
- Declare the volume at the bottom of the file, under a volumes block.
- docker compose down -v removes the named volumes too.
In this example, Compose starts Postgres with its password from the file and its data in a named volume. The query answers 1, which proves the database runs with the given password. docker compose down then stops the services.
Note
A .env file holds secrets in plain text. Keep it out of git with .gitignore.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Rust Playground
Exercise
Where does a .env file belong in a Compose project?