Skip to main content

PostgreSQL in Docker Compose

Running PostgreSQL using Docker makes it effortless, and it's even easier to run and manage PostgreSQL when using Docker Compose.

Follow these steps to run PostgreSQL with Docker Compose:

  1. Add the service below to a Compose file:
docker-compose.yml
services:
postgres:
image: postgres:16-alpine
volumes:
- ./mounted_data/postgres/data:/var/lib/postgresql/data
environment:
POSTGRES_DB: app
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
ports:
- "127.0.0.1:5432:5432"
restart: always
  1. Create the directory on the host where PostgreSQL data will be retained
mkdir -p mounted_data/postgres/data
  1. Start the service
docker compose up -d postgres
  1. Use the following connection string to connect to the database:
postgres://postgres:postgres@localhost:5432/app

(If you're connecting from another container in the same Compose file, use postgres as the hostname instead of localhost)

tip

The service is exposed only to the host machine, so you'll need to SSH into the host to connect from outside the host machine. For example, when using pgAdmin, etc.

info

The postgres user has superuser privileges by default. You should create a new user with limited privileges if needed.