Setting Up Replication in PostgreSQL
Setting Up Replication in PostgreSQL
standby (replica) servers. PostgreSQL supports two main types of replication: physical replication
(streaming replication) and logical replication. In this guide, we'll focus on physical replication, which is
commonly used for high availability (HA) setups.
On the primary server, you need to adjust some configuration settings to enable replication.
2. Enable WAL archiving and configure replication settings: Add or modify the following
parameters:
The pg_hba.conf file controls client authentication, and you need to allow replication connections from the
standby server.
Vi /postgres/pg_data/pg_hba.conf
2. Add a replication entry: Add a line that allows the standby server to connect for replication.
Replace standby_ip_address with the IP address of the standby server:
This allows the standby to connect using an IP address and md5 authentication.
3. Reload PostgreSQL:
To set up replication, the standby needs a copy of the data directory from the primary server.
1. Stop the standby server if it's running:
2. Use the pg_basebackup command to copy the data from the primary to the standby server:
1. Edit postgresql.conf: You need to set up replication parameters on the standby server.
Vi /home/PG/backup/rep/postgresql.conf
or
postgres=#
[postgres@localhost archivelogs]$ psql postgres --port=5434
psql (16.4)
Type "help" for help.
postgres=# \l+
On the primary server, you can check if the standby is connected using the following SQL command:
postgres=#
postgres=#
The closer these two values are, the smaller the lag between the primary and standby.
By default, the standby server in streaming replication mode is read-only. You can connect to the standby
and execute read-only queries, which is useful for load balancing read operations.
Important Considerations:
WAL Retention: Ensure the primary retains enough WAL files to allow the standby to catch up in
case it falls behind. This is controlled by wal_keep_size.
Failover: In case of primary failure, you can promote the standby to a primary by running:
pg_ctl promote -D /postgres/pg_data/standby/data_directory
Monitoring: It's important to monitor the replication status, especially in production environments,
to ensure that the standby is not falling behind.
This is the basic setup for streaming replication. You can extend this with asynchronous/synchronous
replication or implement failover management tools like repmgr or Patroni for automatic failover
handling.