Replication Setup in Postgres Using Docker
Setting Up PostgreSQL Master-Replica Architecture with Docker
Here's a comprehensive step-by-step guide to set up a PostgreSQL master-replica cluster with one master and three replica nodes. We will use postgres asynchronous replication for master and replica
Project Structure Setup
First, ensure your project directory follows this structure:
postgres-replica-demo/
├── docker-compose.yml
├── master/
│ ├── Dockerfile
│ └── init-master.sh
└── replica/
├── Dockerfile
└── docker-entrypoint.shStep 1: Complete the Master Configuration Files
Master Dockerfile
Dockerfile for master database docker instance , it will create image and added sh script as entry point to mark it for master for replication.
./master/Dockerfile:
Master Initialization Script
Here is the bash script that will set replication in master database instance
./master/init-master.sh
Key Configuration Explanations:
wal_level = replica: Enables write-ahead logging for replication
max_wal_senders = 10: Allows up to 10 concurrent replica connections
max_replication_slots = 10: Creates slots for tracking replication progress
synchronous_commit = off: Improves performance by not waiting for replica confirmation
Step 2: Complete the Replica Configuration Files
Replica Dockerfile
Replica container docker file, will create postgres container and run script to mark it as replica.
./replica/Dockerfile:
Replica Entrypoint Script
Replication script that handles the replica initialization:
./replica/docker-entrypoint.sh
Critical Script Components:
pg_isready check: Ensures master is accepting connections before proceeding
pg_basebackup: Creates a physical copy of the master database
-R flag: Automatically configures replication settings
gosu: Ensures PostgreSQL runs with correct user permissions
Step 3: Docker -compose file
The docker-compose file will be responsible for setting infra.
creates master postgres instance running on port 6000
creates 3 replica postgres instance running on port 6001, 6002, 6003
Every container has volume mount so that data is not lost in case of container shut down.
Step 4: Deploy the Cluster
Build and Start Services
Verify Container Status
Step 5: Verification and Testing
Test Master Database Connection
Verify Replication Status on Master
Test Read Operations on Replicas
Test Replication Lag
Step 6: Performance Monitoring and Health Checks
Create Monitoring Scripts
Create a monitor.sh script for ongoing health checks:
Troubleshooting Common Issues
Replica Startup Failures
Replication Lag Issues
Data Directory Persistence
Your configuration uses named volumes for data persistence:
master-data: Stores master database files
replica1-data, replica2-data, replica3-data: Store replica-specific files
To reset the entire cluster:
This setup provides a robust PostgreSQL master-replica architecture that's perfect for Spring Boot read replica demo, with proper replication monitoring, health checks, and scalability options.
Last updated