Postgres Docker Container Setup
Tags: tech, tech.docker, tech.postgres
I prefer running Postgres databases in Docker containers, instead of with the standalone MacOS app or Linux packages. Configuring and managing Postgres instances with Docker offers a way better dev experience (especially when paired with Postico 2) and has great support for targeting specific versions of Postgres.
Files Needed for a Dockerized Postgres 17 Instance
docker-compose.yml
services:
db:
image: postgres:17-alpine
restart: always
shm_size: 128mb
env_file:
- path: ./.env
required: true
- path: ./.env.local
required: false
volumes:
- ./lib/data/init.sql:/docker-entrypoint-initdb.d/init.sql
- pgdata:/var/lib/postgresql/data
networks:
- app-network
ports:
- "127.0.0.1:5432:5432"
logging:
driver: "json-file"
options:
max-size: "10m"
max-file: "3"
Compose File Notes
- The
env_fileconfig supports an optional.env.localfile to add environment-specific overrides that can/should be added to.gitignore. - The
volumesconfig initializes a new database with a hypotheticalinit.sqlfile. This only occurs when an existing database is not found and it's highly recommended to keep this intact as a "source of truth" for the intended structure of your db. - The
portsconfig only allows access from localhost, which usually means SSH tunneling for deployed environments. If you want to expose your databases externally, simplify the line to just- 5432:5432. - The
loggingconfig utilizes 3x 10mb log files, and will drop the oldest one when all 3 are full. This is to keep log sizes manageable, but depending on how often your app will create logs, you may need to increase these values.
.env
I use an .env file to track the expected/required fields, and override them in an .env.local file with actual logins on a per-environment basis.
This allows me to define the necessary connection values once for use on the Docker container configs and whatever CRUD app I might be building alongside the database.
POSTGRES_DB=db_name
POSTGRES_USER=db_user
POSTGRES_PASSWORD=db_pass
.gitignore
Environment-specific overrides and Postgres database files should not be tracked in git.
.env.local
data
Running The Postgres Docker Image
After setting up the config files above, you can run docker compose up -d in the project root to start the Postgres database instance.
To stop the database instance, run docker compose down in the same directory.