Postgres Docker Container Setup

Created by brian on

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

yaml
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_file config supports an optional .env.local file to add environment-specific overrides that can/should be added to .gitignore.
  • The volumes config initializes a new database with a hypothetical init.sql file. 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 ports config 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 logging config 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.

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

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

Last updated

>

Comments (0)

Loading...

Join the conversation!

Sign up for free to leave a comment.