JavaScript Development Space

How to Setup a Local PostgreSQL Using Docker Compose

Local PostgreSQL Using Docker Compose

Running a PostgreSQL database locally with Docker Compose is an efficient way to manage databases without manual installation. Here’s a step-by-step guide to set it up.

Prerequisites

  • Docker and Docker Compose installed on your machine.

Step 1: Create a Project Directory

Create a new directory for your project to keep all files organized:

mkdir postgres-docker

then

cd postgres-docker

Step 2: Create a docker-compose.yml File

Inside your project directory, create a file named docker-compose.yml and add the following configuration:

yaml
1 version: '3.8'
2
3 services:
4 db:
5 image: postgres:latest
6 container_name: local-postgres
7 environment:
8 POSTGRES_USER: postgres_user
9 POSTGRES_PASSWORD: postgres_password
10 POSTGRES_DB: postgres_db
11 ports:
12 - "5432:5432"
13 volumes:
14 - postgres_data:/var/lib/postgresql/data
15 - ./init.sql:/docker-entrypoint-initdb.d/init.sql # Optional: initialize with SQL script
16
17 volumes:
18 postgres_data:

Environment Variables:

  • POSTGRES_USER: Set the username for the PostgreSQL instance.

  • POSTGRES_PASSWORD: Set the password for the PostgreSQL instance.

  • POSTGRES_DB: Set the default database to be created.

  • Ports: The 5432:5432 mapping lets you access the database locally on port 5432.

Volumes:

  • postgres_data: Persist PostgreSQL data even after stopping the container.
  • init.sql: Optional SQL script that runs automatically when the container starts (you can customize this file for initial configurations).

Step 3: Start the PostgreSQL Service

Run the following command to start the PostgreSQL container with Docker Compose:

docker-compose up -d

This command pulls the PostgreSQL image, creates the container, and starts it in detached mode (-d).

Step 4: Connect to PostgreSQL

Once the container is running, connect to PostgreSQL from your local machine using a tool like psql or a database GUI like DBeaver or pgAdmin.

Using psql Command:

psql -h localhost -p 5432 -U postgres_user -d postgres_db

Replace postgres_user and postgres_db with the values from your docker-compose.yml file.

Step 5: Stop and Remove the Container (Optional)

To stop and remove the container, use:

docker-compose down

This command will stop the PostgreSQL container and remove it but keep the volume data intact for reuse.

Summary

Setting up PostgreSQL with Docker Compose allows you to manage your database locally with ease. By following these steps, you’ll have a fully functional PostgreSQL instance running on your machine without the need for manual installation.

JavaScript Development Space

© 2024 JavaScript Development Space - Master JS and NodeJS. All rights reserved.