A Simple Guide to Setting Up PostgreSQL with Docker

When working with databases like PostgreSQL, setting up your environment efficiently can save you a lot of time. In this guide, we’ll cover setting up PostgreSQL with Docker.

Docker PostgreSQL Setup

Setting Up PostgreSQL with Docker

Docker is an excellent choice for creating isolated, repeatable development environments. It saves you a lot of time and effort, and you can run your environment without polluting your local machine with dependencies and configurations of all the projects you work on.

Prerequisites:

Download the docker desktop application for your operating system from the official docker website.

1. Pull the PostgreSQL Image

Download the official PostgreSQL image from Docker Hub:

docker pull postgres

2. Create a Volume

Persist data across container restarts by creating a Docker volume:

docker volume create postgres-data

3. Run the Container

Start a new PostgreSQL container with the created volume:

docker run --name postgres-container -e POSTGRES_PASSWORD=postgres -p 5432:5432 -v postgres-data:/var/lib/postgresql/data -d postgres

this command will run the postgres container and create a volume for the database data.

  • -e POSTGRES_PASSWORD=postgres flag is used to set the password for the postgres user.
  • -p 5432:5432 flag is used to map the container's port 5432 to the host's port 5432.
  • -v postgres-data:/var/lib/postgresql/data flag is used to mount the volume to the container.
  • -d postgres flag is used to run the container in detached mode.

Verify the container is running:

docker ps

4. Access the PostgreSQL Shell

Connect to the PostgreSQL instance:

docker exec -it postgres-container psql -U postgres

From here, you can run SQL commands, create databases, and more:

CREATE DATABASE app;

5. Restore a Database Dump

If you have a dump file, follow these steps:

Copy the Dump File into the Container

docker cp app.dump postgres-container:/app.dump

Restore the Dump

docker exec -it postgres-container pg_restore -U postgres -d app /app.dump

6. Updating or Restoring a Backup

To restore a new dump file, we can use a simple bash script:

#!/bin/bash

docker stop postgres-container
docker exec -it postgres-container rm /app.dump
docker cp app.dump postgres-container:/app.dump
docker exec -it postgres-container pg_restore -U postgres -d app /app.dump
docker start postgres-container