How to start a local PostgreSQL database with Docker

Bjorn Krols

Bjorn Krols

Published on
27 July 2021

Basic setup

docker-compose.yml

version: "3"
services:
  postgres:
    image: "postgres"
    container_name: "postgres"
    environment:
      - POSTGRES_USER=john
      - POSTGRES_PASSWORD=shhhht
      - POSTGRES_DB=project
    ports:
      - 5432:5432

Note: a default database called postgres will be created.

Interacting with the service

To start the service:

docker compose up -d

To stop the service:

docker compose down

Working with the PostgreSQL shell

To access the shell:

docker exec -it postgres psql project -U john
  • docker exec -it - run a command to a running container
  • postgres - the container name
  • psql - the command
  • project - the database you want to connect to
  • -U john - the user

To exit the shell:

exit

Overriding configuration parameters

version: "3"
services:
  postgres:
    image: "postgres"
    container_name: "postgres"
    command:
      - "postgres"
      - "-c"
      - "log_connections=yes"
      - "-c"
      - "max_connections=1337"
    environment:
      - POSTGRES_USER=john
      - POSTGRES_PASSWORD=shhhht
      - POSTGRES_DB=project
    ports:
      - 5432:5432

Using a custom Dockerfile

docker-compose.yml

version: "3"
services:
  postgres:
    build: .
    container_name: "postgres"
    environment:
      - POSTGRES_USER=john
      - POSTGRES_PASSWORD=shhhht
      - POSTGRES_DB=project
    ports:
      - 5432:5432

Dockerfile

FROM postgres:14
RUN apt-get update
RUN apt-get install -y postgresql-14-wal2json

Subscribe to our newsletter

The latest news, articles, and resources, sent to your inbox weekly.

More like this