Run PostgreSQL in Docker for local development in under 5 minutes

September 27, 2020 ☼ Docker

I recently had to spin up a PostgreSQL database for a project I’m currently working on. In this post I’ll show you how to quickly do the same.

Install Docker

Download docker here.

Enter Docker Compose

We’re going to use Docker compose to set up everything. It’s totally fine to run Postgres with a single Docker command but in this case I’d like to add PgAdmin as an admin tool and God only knows how many other services we’re going to add further down the line ;) …right?

It’s easier to manage multiple services with Docker compose. With Compose, you use a YAML file to configure your application’s services (works in all environments).

Create a docker-compose.yml file

version: "3.1"
services:
  db:
    image: "postgres:13"
    container_name: "db_postgres"
    environment:
      POSTGRES_USER: ${POSTGRES_USER}
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER}"]
      interval: 30s
      timeout: 30s
      retries: 5
    ports:
      - "5432:5432"
    restart: always
    volumes:
      - db_dbdata:/var/lib/postgresql/data
  
  pgadmin:
    container_name: pgadmin_container
    image: dpage/pgadmin4
    environment:
      PGADMIN_DEFAULT_EMAIL: ${PGADMIN_DEFAULT_EMAIL}
      PGADMIN_DEFAULT_PASSWORD: ${PGADMIN_DEFAULT_PASSWORD}
    volumes:
      - pgadmin:/root/.pgadmin
    ports:
      - "8000:80"
    restart: always

volumes:
  db_dbdata:
  pgadmin:

What happens in that file:

ENV variables

The strings inside ${ } refer to ENV variables. The PostgreSQL image uses several environment variables which are easy to miss. While none of the variables are required, they may significantly aid you in using the image.

In this case I exported the ENV variables in my shell so Compose will pick them up automatically.

# CHANGE them as you see fit

export POSTGRES_USER=myUser
export POSTGRES_PASSWORD=root
export POSTGRES_DB=db
export PGADMIN_DEFAULT_EMAIL=pgadmin4@pgadmin.org
export PGADMIN_DEFAULT_PASSWORD=admin

You can also create a .env file or take a look at the documentation for more ways of handling ENV vars.

Run services

psql (13.0 (Debian 13.0-1.pgdg100+1))
Type "help" for help.

myUser=#

You are all set!

Other useful commands


If you have any suggestions, questions, corrections or if you want to add anything please DM or tweet me: @zanonnicolas