In this guide, we are setting up a highly available PostgreSQL cluster using several key components: Patroni, etcd, HAProxy, and Keepalived. Patroni is a template for PostgreSQL high availability, allowing us to manage PostgreSQL clusters with automatic failover. etcd is a distributed key-value store that provides a reliable way to store data across a cluster of machines, ensuring that Patroni can maintain consensus on the state of the cluster. HAProxy is a high-performance TCP/HTTP load balancer that will distribute database connections across the PostgreSQL nodes, ensuring that read and write operations are directed appropriately. Finally, Keepalived is used to manage a virtual IP (VIP) that provides a single, consistent endpoint for database connections, even in the event of node failures. By following this guide, you will learn how to configure and integrate these components to create a robust and resilient PostgreSQL cluster suitable for production environments.
Architecture
The cluster consists of:
3 PostgreSQL nodes with Patroni
Distributed etcd cluster
HAProxy on each node
Keepalived for VIP management
Virtual IP (VIP) for high availability
Node Name
Role
IP Address
PostgreSQL + Patroni + etcd
PostgreSQL + Patroni + etcd
PostgreSQL + Patroni + etcd
pgBackRest + PMM Server
Virtual IP
High Availability Endpoint
Note: The VIP is used as the primary connection endpoint for applications.
Architecture Diagram
The following diagram illustrates the complete node architecture of our PostgreSQL high availability setup:
Figure 1: PostgreSQL HA Cluster Node Architecture showing all components distributed across nodes
The diagram shows how each component is distributed across the different nodes:
**, , **: Each database node contains PostgreSQL, Patroni, etcd, HAProxy, Keepalived, and PMM Client
****: Dedicated backup node running pgBackRest and PMM Server
**Virtual IP ()**: Floating IP that provides a stable connection endpoint for applications
This architecture ensures high availability with automatic failover capabilities, comprehensive backup solutions, and performance monitoring.
Note: To regenerate this diagram if needed, you can use the Mermaid Live Editor with the diagram code available in the documentation source.
Prerequisites
Before starting the setup, ensure you have the following:
Ubuntu 22.04 or later
Sudo privileges on all nodes
Network connectivity between nodes
Required ports:
PostgreSQL: 5432
Patroni: 8008
etcd: 2379, 2380
HAProxy: 5433
Keepalived: VRRP (112)
Initial Setup
In this part, we will configure the basic environment settings, including hostname configuration and package installation. These are needed to prepare the nodes for the subsequent steps.
Hostname Configuration
Set the hostname on each node:
1
2
3
4
5
6
# On respective nodessudo hostnamectl set-hostname <REDACTED_HOSTNAME> # For node 1sudo hostnamectl set-hostname <REDACTED_HOSTNAME> # For node 2sudo hostnamectl set-hostname <REDACTED_HOSTNAME> # For node 3
Note: Replace <REDACTED_HOSTNAME>, <REDACTED_HOSTNAME>, and <REDACTED_HOSTNAME> with the actual hostnames.
Update /etc/hosts on all nodes:
1
2
3
4
# Add to /etc/hosts
<REDACTED_IP> <REDACTED_HOSTNAME>
<REDACTED_IP> <REDACTED_HOSTNAME>
<REDACTED_IP> <REDACTED_HOSTNAME>
Note: Replace IP addresses with the actual IP addresses of the nodes.
The etcd cluster is a critical component in the Patroni architecture, serving as the distributed key-value store that enables high availability and automatic failover capabilities for PostgreSQL.
Key Functions
Maintains cluster state information
Handles leader election processes
Stores configuration data
Enables distributed consensus among nodes
Configuration Requirements
Each node in the cluster requires:
Unique etcd instance
Individual configuration file
Distinct network endpoints
Specific cluster membership settings
Important Considerations
Minimum of 3 nodes recommended for fault tolerance
Network connectivity between all nodes is essential
Proper security configuration (TLS certificates if needed)
Adequate storage for etcd data
Best Practices
Use dedicated hosts for etcd when possible
Implement proper backup strategies
Monitor etcd cluster health
Configure appropriate timeouts and heartbeat intervals
The etcd cluster provides the distributed consensus mechanism required for Patroni. Each node needs its own etcd configuration.
[Previous sections remain the same up to Patroni Configuration]
Patroni Configuration
Patroni, is a robust PostgreSQL high-availability solution.
Technical Details
Patroni provides:
Real-time replication monitoring
Automatic primary-replica synchronization
Health check mechanisms
Dynamic configuration management
Implementation Significance
The system ensures continuous database availability through:
Seamless failover processes
Consistent data replication
Reliable cluster state management
This configuration is essential for maintaining robust database operations in production environments.
Environment Setup
First, set up environment variables on each node:
1
2
3
4
5
6
7
8
9
10
11
# Set node name and IPexport NODE_NAME=$(hostname-f)export NODE_IP=$(hostname-i | awk'{print $1}')# Set PostgreSQL pathsexport DATA_DIR="/var/lib/postgresql/12/main"export PG_BIN_DIR="/usr/lib/postgresql/12/bin"# Set cluster informationexport NAMESPACE="kyc"export SCOPE="kyc"
Note: Replace the values with your own.
Create Patroni Configuration
Create the Patroni configuration file (/etc/patroni/patroni.yml):
You need to restore the some data from a backup of the previous PostgreSQL cluster to the new cluster. Here are the steps to do that.
Backup the Data from the Previous Cluster
Login as postgres user in bash and backup the schema data and schema only data of kyc, and .
1
2
3
4
5
6
7
8
9
10
# Log into the previous PostgreSQL cluster and switch to postgres bash user.sudo su - postgres
# Backup the <REDACTED_USERNAME> schema data
pg_dump -h localhost -U kyc -d postgres -f <REDACTED_USERNAME>_full.sql
# Backup the schema only data of kyc, <REDACTED_USERNAME> and <REDACTED_USERNAME>
pg_dump -h localhost -U kyc -d postgres -s-f kyc_schema.sql
pg_dump -h localhost -U kyc -d postgres -s-f <REDACTED_USERNAME>_schema.sql
pg_dump -h localhost -U kyc -d postgres -s-f <REDACTED_USERNAME>_schema.sql
Backup 2 tables (kyc.asp_config, kyc.asp_config_id_seq) in kyc schema, as these tables are not part of the schema only data.
1
2
# Backup the kyc.asp_config and kyc.asp_config_id_seq tables
pg_dump -h localhost -U kyc -d postgres -t kyc.asp_config -t kyc.asp_config_id_seq -f kyc_tables.sql
Copy the backup files to the new cluster nodes. Using your preferred method, copy the backup files to the new cluster nodes.
Create users and restore the data in the new cluster
We need this three user in our new cluster. Those are <REDACTED_USERNAME>, <REDACTED_USERNAME>, kyc and <REDACTED_USERNAME>. Lets create these users in the new cluster.
Create the users in the new cluster.
1
2
3
4
5
6
7
8
# Log into the new cluster and switch to postgres bash user.sudo su - postgres
# Create the users
psql -d postgres -c"CREATE USER <REDACTED_USERNAME> SUPERUSER CREATEDB CREATEROLE;"
psql -d postgres -c"CREATE USER <REDACTED_USERNAME> SUPERUSER CREATEDB CREATEROLE;"
psql -d postgres -c"CREATE USER <REDACTED_USERNAME> SUPERUSER CREATEDB CREATEROLE;"
psql -d postgres -c"CREATE USER <REDACTED_USERNAME> SUPERUSER CREATEDB CREATEROLE PASSWORD '<REDACTED_PASSWORD>';"
Restore the data in the new cluster.
1
2
3
4
5
6
7
8
9
10
11
12
13
# Log into the new cluster and switch to postgres bash user.sudo su - postgres
# Restore the <REDACTED_USERNAME> schema data
psql -d postgres -f <REDACTED_USERNAME>_full.sql
# Restore the schema only data of kyc, <REDACTED_USERNAME> and <REDACTED_USERNAME>
psql -d postgres -f kyc_schema.sql
psql -d postgres -f <REDACTED_USERNAME>_schema.sql
psql -d postgres -f <REDACTED_USERNAME>_schema.sql
# Restore the kyc.asp_config and kyc.asp_config_id_seq tables
psql -d postgres -f kyc_tables.sql
Test and verify the data in the new cluster.
1
2
3
4
5
6
7
8
9
10
11
12
13
# Log into the new cluster and switch to postgres bash user.sudo su - postgres
# Connect to the database and verify the data
psql -d postgres -c"\dt"
psql -d postgres -c"SELECT * FROM kyc.asp_config;"
psql -d postgres -c"SELECT * FROM kyc.asp_config_id_seq;"# Check if the schema data is restored correctly
psql -d postgres -c"\dt <REDACTED_USERNAME>.*"
psql -d postgres -c"\dt kyc.*"
psql -d postgres -c"\dt <REDACTED_USERNAME>.*"
psql -d postgres -c"\dt <REDACTED_USERNAME>.*"
pgBackRest Setup
This section covers setting up pgBackRest on a dedicated backup server to provide backup and recovery capabilities for your PostgreSQL cluster. The prerequisites are given below.
A dedicated server for pgBackRest (referred to as )
SSH access between PostgreSQL nodes and the backup server
Sufficient storage space for backups on
Host Configuration
Update the hosts file on the backup server:
1
2
3
4
5
# Add to /etc/hosts on <REDACTED_HOSTNAME>
<REDACTED_IP> <REDACTED_HOSTNAME>
<REDACTED_IP> <REDACTED_HOSTNAME>
<REDACTED_IP> <REDACTED_HOSTNAME>
<REDACTED_IP> <REDACTED_HOSTNAME>
# Edit the crontab for the postgres usersudo crontab -u postgres -e# Add the following line to schedule a daily backup at 2 AM
0 2 *** /usr/bin/pgbackrest --stanza=kyc --type=full backup
Monitor the backup logs:
1
2
# Check the backup logssudo tail-f /var/log/pgbackrest/pgbackrest.log
Test the restore process:
1
2
3
4
5
6
7
8
# Stop the PostgreSQL service on the primary nodesudo systemctl stop patroni
# Restore the backupsudo-u postgres pgbackrest --stanza=kyc restore
# Start the PostgreSQL servicesudo systemctl start patroni
# Check the status of the Patroni cluster
patronictl -c /etc/patroni/patroni.yml list
Monitoring PostgreSQL with Percona Monitoring and Management (PMM)
This section covers setting up Percona Monitoring and Management (PMM) to monitor your PostgreSQL cluster, providing insights into performance, health, and resource utilization. The prerequisites are given below.
A dedicated server for PMM Server (can be installed on )
Network connectivity between PostgreSQL nodes and PMM server
sudo-u postgres psql -c"CREATE USER <REDACTED_USERNAME> WITH SUPERUSER PASSWORD '<REDACTED_PASSWORD>';"||sudo-u postgres psql -c"ALTER USER <REDACTED_USERNAME> WITH SUPERUSER PASSWORD '<REDACTED_PASSWORD>';"
Update pg_hba.conf to allow PMM user local access:
1
2
# Add this line to /var/lib/postgresql/12/main/pg_hba.confecho"local all <REDACTED_USERNAME> md5" | sudo tee-a /var/lib/postgresql/12/main/pg_hba.conf
Enable pg_stat_monitor in shared_preload_libraries:
By following this guide, you have successfully set up a highly available PostgreSQL cluster using Patroni, etcd, HAProxy, and Keepalived. This configuration provides automatic failover, load balancing, and high availability for PostgreSQL databases, ensuring that your applications can rely on a robust and resilient database infrastructure. You can now deploy your applications with confidence, knowing that your database cluster is capable of handling failures and maintaining consistent performance under various conditions.
This documentation provides detailed steps on how to set up RSync in Kubernetes (K8s) to copy pgBackRest backup files to a new replicaABC. It will aslo help you set up PostgreSQ...
This comprehensive guide provides end-to-end instructions for deploying a resilient PostgreSQL cluster using the Crunchy Data PostgreSQL Operator on Kubernetes. The solution int...