How to Setup a 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:
then
Step 2: Create a docker-compose.yml File
Inside your project directory, create a file named docker-compose.yml
and add the following configuration:
1 version: '3.8'23 services:4 db:5 image: postgres:latest6 container_name: local-postgres7 environment:8 POSTGRES_USER: postgres_user9 POSTGRES_PASSWORD: postgres_password10 POSTGRES_DB: postgres_db11 ports:12 - "5432:5432"13 volumes:14 - postgres_data:/var/lib/postgresql/data15 - ./init.sql:/docker-entrypoint-initdb.d/init.sql # Optional: initialize with SQL script1617 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:
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:
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:
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.