Environment
Docker Compose offers a few management options for secrets like database passwords and API keys that you don’t want to commit to version control. We’ll just use a simple approach here to set the Postgres password.
Newer versions of Docker Compose will automatically load environment variables from a .env
file and make them available to the docker-compose.yml file.
POSTGRES_PASSWORD=actually_secret_password
version: '3.8'
services:
web:
build: ./web-app
ports:
- '3000:3000'
environment:
- POSTGRES_PASSWORD
depends_on:
- db
db:
image: postgres:16.0
environment:
- POSTGRES_PASSWORD
- PGDATA=/pg-data
volumes:
- './pg-data:/pg-data'
(Note that if you’ve already run the container once with a different password, you’ll have to change it or reset the database by deleting the pg-data
folder to get this to work.)
When I’m using .env
files for secrets, I always add them to my .gitignore (of course!) and create a .env.example
file that other users can clone to .env
which shows which variables need to be set. This can also be a good way to let users change things about your container setup (like which port your web
container binds to) without having to modify docker-compose.yml directly. You can interpolate values into your configuration from the environment, then let .env.example
serve as a directory of variables the user might be interested in changing.