Skip to content

bikirandev/docker-pgsql

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

11 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Docker PostgreSQL Setup

A production-ready Docker Compose configuration for PostgreSQL with security best practices and health monitoring.

Features

  • 🐘 Latest PostgreSQL image
  • πŸ”’ Localhost-only binding for enhanced security
  • πŸ”„ Automatic restart on failure
  • πŸ’Ύ Persistent data storage with named volumes
  • πŸ₯ Built-in health checks
  • βš™οΈ Fully configurable via environment variables

Prerequisites

Quick Start

1. Clone or Download

git clone https://github.com/bikirandev/docker-pgsql
cd docker-pgsql

2. Configure Environment

Copy the example environment file and customize it:

cp .env.example .env

Edit .env with your preferred values:

CONTAINER_NAME=postgres-container
POSTGRES_DB=mydatabase
POSTGRES_USER=myuser
POSTGRES_PASSWORD=your_secure_password_here
POSTGRES_INITDB_ARGS=
POSTGRES_PORT=5432
VOLUME_NAME=postgres_data_volume

3. Start PostgreSQL

docker-compose up -d

4. Verify Container is Running

docker ps

You should see your PostgreSQL container running with a healthy status.

Environment Variables

Variable Description Default Required
CONTAINER_NAME Name of the Docker container postgres-container Yes
POSTGRES_DB Default database name to create mydatabase Yes
POSTGRES_USER PostgreSQL superuser name myuser Yes
POSTGRES_PASSWORD PostgreSQL superuser password mypassword Yes
POSTGRES_INITDB_ARGS Additional initialization arguments (empty) No
POSTGRES_PORT Host port to expose PostgreSQL 5432 Yes
VOLUME_NAME Name of the Docker volume for data persistence postgres_data_volume Yes

POSTGRES_INITDB_ARGS Examples

# Set encoding and locale
POSTGRES_INITDB_ARGS=--encoding=UTF8 --locale=en_US.UTF-8

# Enable data checksums
POSTGRES_INITDB_ARGS=--data-checksums

Docker Compose Commands

Start the Container

# Start in detached mode
docker-compose up -d

# Start with logs visible
docker-compose up

Stop the Container

docker-compose stop

Stop and Remove Container

docker-compose down

Stop and Remove Container + Volume (⚠️ Deletes all data)

docker-compose down -v

View Logs

# Follow logs in real-time
docker-compose logs -f

# View last 100 lines
docker-compose logs --tail=100

Restart the Container

docker-compose restart

Connecting to PostgreSQL

From Host Machine

Using psql (Command Line)

psql -h localhost -p 5432 -U myuser -d mydatabase

Connection String

postgresql://myuser:mypassword@localhost:5432/mydatabase

Connection Parameters

  • Host: localhost or 127.0.0.1
  • Port: 5432 (or your custom port from .env)
  • Database: Value from POSTGRES_DB
  • Username: Value from POSTGRES_USER
  • Password: Value from POSTGRES_PASSWORD

From Another Docker Container

If you have other containers in the same Docker Compose network:

services:
  your-app:
    # ... other configuration
    environment:
      DATABASE_URL: postgresql://myuser:mypassword@postgres:5432/mydatabase

Note: Use the service name (postgres) as the hostname, not localhost.

Using GUI Tools

Popular PostgreSQL GUI tools that work with this setup:

Health Check

The container includes an automatic health check that:

  • Runs every 10 seconds
  • Uses pg_isready to verify PostgreSQL is accepting connections
  • Allows 5 retries before marking as unhealthy
  • Has a 5-second timeout per check

Check container health status:

docker inspect --format='{{.State.Health.Status}}' <container-name>

Data Persistence

PostgreSQL data is stored in a named Docker volume (postgres_data_volume by default). This ensures your data persists even if the container is removed.

Backup Data

# Create a backup
docker exec -t <container-name> pg_dumpall -c -U myuser > backup.sql

# Or backup a specific database
docker exec -t <container-name> pg_dump -U myuser mydatabase > mydatabase_backup.sql

Restore Data

# Restore from backup
cat backup.sql | docker exec -i <container-name> psql -U myuser

# Or restore specific database
cat mydatabase_backup.sql | docker exec -i <container-name> psql -U myuser -d mydatabase

Volume Location

To find where Docker stores the volume on your system:

docker volume inspect postgres_data_volume

Security Considerations

Current Security Features

βœ… Localhost-only binding: PostgreSQL is only accessible from the host machine, not from external networks.

βœ… Non-root user: Container runs as the postgres user for enhanced security.

βœ… Health monitoring: Automatic health checks ensure the database is running properly.

Additional Security Recommendations

  1. Strong Password: Use a strong, unique password in your .env file
  2. Environment File: Never commit .env to version control
  3. SSL/TLS: For production, configure SSL certificates
  4. Firewall: Ensure your host firewall is properly configured
  5. Updates: Regularly update to the latest PostgreSQL image

.gitignore

Add these lines to your .gitignore:

.env
*.sql
backup/

Troubleshooting

Container Won't Start

Check logs for errors:

docker-compose logs postgres

Permission Denied Errors

Ensure Docker has permission to create volumes:

docker-compose down -v
docker-compose up -d

Cannot Connect to Database

  1. Verify container is running: docker ps
  2. Check health status: docker inspect --format='{{.State.Health.Status}}' <container-name>
  3. Verify port is not in use: netstat -an | grep 5432 (Windows) or lsof -i :5432 (Linux/Mac)
  4. Check environment variables in .env file

Port Already in Use

If port 5432 is already in use, change POSTGRES_PORT in your .env file:

POSTGRES_PORT=5433

Then restart:

docker-compose down
docker-compose up -d

Advanced Configuration

Custom PostgreSQL Configuration

Create a custom postgresql.conf file and mount it:

volumes:
  - postgres_data:/var/lib/postgresql/data
  - ./postgresql.conf:/etc/postgresql/postgresql.conf

Initialization Scripts

To run SQL scripts on first startup, mount them to /docker-entrypoint-initdb.d/:

volumes:
  - postgres_data:/var/lib/postgresql/data
  - ./init-scripts:/docker-entrypoint-initdb.d

Multiple Databases

Create an initialization script init-scripts/create-databases.sh:

#!/bin/bash
set -e

psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "$POSTGRES_DB" <<-EOSQL
    CREATE DATABASE app_db;
    CREATE DATABASE test_db;
EOSQL

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

Support

If you encounter any issues or have questions:

  1. Check the Troubleshooting section
  2. Review PostgreSQL Docker Hub documentation
  3. Open an issue in this repository

Resources


πŸ“„ License

MIT License - see the LICENSE file for details.

πŸ‘¨β€πŸ’» Author

Developed by Bikiran



🏒 About Bikiran

Bikiran is a software development and cloud infrastructure company founded in 2012, headquartered in Khulna, Bangladesh. With 15,000+ clients and over a decade of experience, Bikiran builds and operates a suite of products spanning domain services, cloud hosting, app deployment, workflow automation, and developer tools.

SL Topic Product Description
1 Website Bikiran Main platform β€” Domain, hosting & cloud services
2 Website Edusoft Education management software for institutions
3 Website n8n Clouds Managed n8n workflow automation hosting
4 Website Timestamp Zone Unix timestamp converter & timezone tool
5 Website PDFpi Online PDF processing & manipulation tool
6 Website Blog Technical articles, guides & tutorials
7 Website Support 24/7 customer support portal
8 Website Probackup Automated database backup for SQL, PostgreSQL & MongoDB
9 Service Domain Domain registration, transfer & DNS management
10 Service Hosting Web, app & email hosting on NVMe SSD
11 Service Email & SMS Bulk email & SMS notification service
12 npm Chronopick Date & time picker React component
13 npm Rich Editor WYSIWYG rich text editor for React
14 npm Button Reusable React button component library
15 npm Electron Boilerplate CLI to scaffold Electron.js project templates
16 NuGet Bkash bKash payment gateway integration for .NET
17 NuGet Bikiran Engine Core .NET engine library for Bikiran services
18 Open Source PDFpi PDF processing tool β€” open source
29 Open Source Bikiran Engine Core .NET engine β€” open source
20 Open Source Drive CLI CLI tool to manage Google Drive from terminal
21 Docker Pgsql Docker setup for PostgreSQL
22 Docker n8n Docker setup for n8n automation
23 Docker Pgadmin Docker setup for pgAdmin
24 Social Media LinkedIn Bikiran on LinkedIn
25 Social Media Facebook Bikiran on Facebook
26 Social Media YouTube Bikiran on YouTube
27 Social Media FB n8nClouds n8n Clouds on Facebook

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors