
This assumes you have installed HAProxy.
HAProxy is a service that can be used to load balance requests between a TCP service. For example, let's say you have two or more Postgres databases. HAProxy can be used to load balance the requests across the two databases, using Round Robin or Least Connections.
If you have a firewall, such as iptables or firewalld, assuming your Postgres databases are listening on default port 5432, allow port 5432 in the firewall.
firewall-cmd --add-port=5432/tcp --permanent
firewall-cmd --reload
Let's say you want requests submitted into HAProxy on port 5432 (frontend) to be forwarded to the Postgres databases on port 5432 (backend), using round robin for load balancing. In this scenario, the frontend and backend blocks in haproxy.cfg would contain something like this. Let's break this down.
- The listener is named "postgres". This can be any name you want, it just has to be something unique.
- The listener is listening on *:5432, meaning that any interface / IP address on the HAProxy server on port 5432.
- round robin for load balancing.
- The first server is the Postgres database at 10.0.0.7
- The second server is the Postgres database at 10.0.0.8
listen postgres
bind *:5432
mode tcp
balance roundrobin
server db1 10.0.0.7:5432 check
server db2 10.0.0.8:5432 check
Or like this.
frontend postgres
bind *:5432
default_backend postgres_db
backend postgres_db
balance roundrobin
server db1 10.0.0.7:5432 check
server db2 10.0.0.8:5432 check
Restart HAProxy for this change to take effect.
systemctl restart haproxy
Did you find this article helpful?
If so, consider buying me a coffee over at