Setting up PostgreSQL with Streaming Replication for High Availability and Failover involves several key steps. This guide will walk you through the process, step by step.
Edit postgresql.conf
:
listen_addresses
to '*'
or the specific IP address to allow connections.wal_level
to replica
or logical
.max_wal_senders
to a number greater than the number of standby servers.wal_keep_size
to specify the amount of WAL files to keep.Edit pg_hba.conf
:
Add a line to allow the standby server to connect.
host replication <replication_user> <standby_ip>/32 md5
<replication_user>
is the user for replication, and <standby_ip>
is the IP address of the standby server.
Create a Replication Role:
Connect to the primary database and execute:
CREATE ROLE <replication_user> REPLICATION LOGIN ENCRYPTED PASSWORD '<password>';
Restart PostgreSQL.
Use pg_basebackup
to copy data:
pg_basebackup -h <primary_ip> -D <standby_data_directory> -U <replication_user> -P -v -R
Replace <primary_ip>
, <standby_data_directory>
, and <replication_user>
with your values.
Edit postgresql.conf
(if not already done by pg_basebackup
):
hot_standby
to on
.Create standby.signal
File:
standby.signal
.Optional Configuration in recovery.conf
:
If specific recovery parameters are needed, create a recovery.conf
in the data directory.
Set primary_conninfo
with the connection string to the primary server.
primary_conninfo = 'host=<primary_ip> port=5432 user=<replication_user> password=<password>'
Start PostgreSQL on the standby server.
Check the Logs:
Check Replication Status on Primary:
Connect to the primary database and query:
SELECT * FROM pg_stat_replication;
Check Standby Status:
Streaming Replication in PostgreSQL provides a robust solution for high availability and failover. It's important to test the setup thoroughly and simulate failover scenarios to ensure the system behaves as expected under different conditions. Regular monitoring, backups, and updates are essential to maintain the health and performance of the replication setup.