Set up Postgres in Docker locally

3 Easy ways to run postgres locally for testing database.

LinkIconFirst way

Testing Database installation in Docker guide- here

LinkIconSecond way

LinkIconCreate docker file

Copy and paste the following in the root of your project directory.

services:
  db:
    image: postgres:16.2
    environment:
      - POSTGRES_PASSWORD=${DB_PASSWORD}
      - POSTGRES_USER=${DB_USER}
      - POSTGRES_DB=${DB_NAME}
    ports:
      - ${DB_PORT}:5432
    volumes:
      - ./db-data:/var/lib/postgresql/data

LinkIconSet Environment Variables

DB_HOST=
DB_USER=
DB_PASSWORD=
DB_NAME=
DB_PORT=
 
DATABASE_URL=postgresql://${DB_USER}:${DB_PASSWORD}@${DB_HOST}:${DB_PORT}/${DB_NAME}

LinkIconRun

Run the docker with this command

docker compose up

LinkIconTo remove a container

rm -rf db-data

LinkIconThird way

Reference

Create a docker-compose.yml

version: '3'
services:
	db:
		image: postgres
		restart: always
		volumes:
			- ./data/db:/var/lib/postgresql/data
		ports:
			- 5432:5432
		environment:
			- POSTGRES_DB=testDB
			- POSTGRES_USER=postgres
			- POSTGRES_PASSWORD=postgres
	## GUI
	adminer:
		image: adminer
		restart: always
		ports:
			- 8080:8080

Run docker

docker compose up

Open localhost:8080 to open the adminer GUI. Then, enter credentials