PostgreSQL replication is a robust solution for ensuring database availability, load balancing, and failover readiness. This guide provides a step-by-step approach to setting up Master-Slave replication on Debian 12, using PostgreSQL 15, along with hostname-based configurations.

1. System Prerequisites

1.1 Server Environment

We will use four Debian 12 servers with PostgreSQL 15 installed:

  • Master: postgre.master.x1.demo.internal (10.11.33.53)
  • Slave 1: postgre.slave.x1.demo.internal (10.11.33.66)
  • Slave 2: postgre.slave.x2.demo.internal (10.11.33.67)
  • Slave 3: postgre.slave.x3.demo.internal (10.11.33.68)

1.2 Update Hostname Configuration

Ensure that your /etc/hosts file includes the following lines:

2. Install PostgreSQL on All Servers

3. Configure the Master Server

3.1 Enable Replication Settings

Modify the PostgreSQL configuration file on the master:

Ensure these settings are applied:

Create the archive directory:

3.2 Configure Authentication

Modify the pg_hba.conf file to allow replication:

Add these lines:

3.3 Restart the PostgreSQL Service

3.4 Create Replication User

Switch to the PostgreSQL user and execute:

4. Configure the Slave Servers

4.1 Stop PostgreSQL on the Slaves

4.2 Remove Existing Data

4.3 Synchronize Data from Master

4.4 Create Standby Signal (If Needed)

4.5 Configure Connection to Master

Edit postgresql.conf on each slave:

4.6 Restart PostgreSQL on the Slaves

5. Verify Replication

5.1 Check Master Replication Status

On the master, run:

5.2 Check Slave Replication Status

On each slave, run:

If replication is active, the output should be true.

5.3 Test Replication

On the master, create a test database and table:

On each slave, verify the data exists:

6. Monitoring & Maintenance

6.1 Monitor Logs

6.2 Set Up Automated Failover (Optional)

Consider using pg_auto_failover or Patroni for automated failover.

6.3 Schedule Regular Backups

Even with replication, backups are necessary. Use:

6.4 Automate WAL Cleanup

To prevent excessive storage usage, set up a cron job to delete old WAL files:

Add the following line to remove WAL files older than 7 days:

This will run daily at 3 AM to free up space while ensuring replication stability.

7. Summary

This guide provides a host-based PostgreSQL Master-Slave replication setup on Debian 12. With real-time data replication, it ensures high availability and disaster recovery. By following these steps, your database cluster is resilient, scalable, and ready for production workloads. 🚀

Leave A Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.