How to Configure a Highly Available HAProxy Load Balancer on CentOS 9

# How to Configure a Highly Available HAProxy Load Balancer on CentOS 9 As web applications scale to handle increased traffic, relying on a single web server creates a critical single point of failure and bottlenecks performance. A load balancer solves this by distributing incoming network traffic across a cluster of backend servers. HAProxy (High Availability Proxy) is an industry-standard, fast, and reliable open-source TCP/HTTP load balancer. It is heavily utilized in enterprise environments to ensure continuous uptime and optimize resource utilization. This guide provides a comprehensive technical workflow for installing and configuring HAProxy on CentOS 9 Stream to load balance web traffic across multiple backend Nginx or Apache servers. ## Architecture Overview For this deployment, we will assume a basic three-tier architecture utilizing three separate CentOS 9 virtual machines: 1. **Load Balancer:** `haproxy-node` (IP: 192.168.1.100) 2. **Backend Web Server 1:** `web-node-01` (IP: 192.168.1.101) 3. **Backend Web Server 2:** `web-node-02` (IP: 192.168.1.102) *Note: Ensure that your backend web servers (web-node-01 and web-node-02) already have a web server (like Nginx or Apache) installed, running, and serving a default webpage so you can verify the load balancing.* ## Step 1: Install HAProxy on CentOS 9 Connect to your designated load balancer node (`haproxy-node`) via SSH. CentOS 9 Stream includes HAProxy in its default repository, making installation straightforward via the `dnf` package manager. 1. **Update the system packages:**

   sudo dnf update -y
   
2. **Install HAProxy:**

   sudo dnf install haproxy -y
   
3. **Verify the installation:** Check the installed version to confirm success.

   haproxy -v
   
## Step 2: Configure the Firewall and SELinux Before configuring HAProxy, you must ensure the network and security layers on the CentOS server will allow traffic to flow through the load balancer. 1. **Open HTTP and HTTPS ports in firewalld:**

   sudo firewall-cmd --permanent --add-service=http
   sudo firewall-cmd --permanent --add-service=https
   sudo firewall-cmd --reload
   
2. **Configure SELinux:** By default, SELinux policies in CentOS are strict. If HAProxy is acting as a reverse proxy, it needs permission to initiate network connections to the backend servers. You must set the `haproxy_connect_any` boolean to true.

   sudo setsebool -P haproxy_connect_any 1
   
## Step 3: Configure the HAProxy Configuration File The behavior of HAProxy is defined in a single configuration file: `/etc/haproxy/haproxy.cfg`. Before making changes, create a backup of the default configuration.

sudo cp /etc/haproxy/haproxy.cfg /etc/haproxy/haproxy.cfg.backup
Open the configuration file in your preferred text editor (e.g., nano or vi).

sudo nano /etc/haproxy/haproxy.cfg
The configuration file is divided into several sections: `global`, `defaults`, `frontend`, and `backend`. We will leave the `global` and `defaults` sections as they are and define our custom frontend and backend routing. Append the following configuration to the end of the file:

# ---------------------------------------------------------------------
# Frontend: Listen for incoming traffic on port 80
# ---------------------------------------------------------------------
frontend http_front
    bind *:80
    
    # Optional: Define ACLs (Access Control Lists) here if needed
    
    # Point all traffic to the backend server pool
    default_backend web_backend

# ---------------------------------------------------------------------
# Backend: Define the pool of web servers
# ---------------------------------------------------------------------
backend web_backend
    # Define the load balancing algorithm
    balance roundrobin
    
    # Define health check parameters
    option httpchk HEAD / HTTP/1.1\r\nHost:\ localhost
    
    # Define the backend servers
    # Format: server <name> <ip>:<port> check
    server web-node-01 192.168.1.101:80 check
    server web-node-02 192.168.1.102:80 check
### Explaining the Configuration: – **`frontend http_front`**: Defines how requests arrive. `bind *:80` tells HAProxy to listen on all available IPv4 interfaces on port 80 (standard HTTP). – **`default_backend web_backend`**: Routes all traffic arriving at the frontend to the backend pool defined below. – **`balance roundrobin`**: This is the load balancing algorithm. Round Robin sends the first request to Server 1, the second to Server 2, the third back to Server 1, and so on evenly. (Other options include `leastconn` for directing traffic to the server with the fewest active connections). – **`option httpchk`**: This enables layer 7 (HTTP) health checking. HAProxy will continuously send HTTP HEAD requests to the root directory of the backend servers. – **`server … check`**: The `check` parameter at the end of the server definition tells HAProxy to actively use the `httpchk` defined above. If a backend server fails to respond, HAProxy will automatically remove it from the pool and redirect all traffic to the remaining healthy servers. ## Step 4: Enable HAProxy Statistics (Optional but Recommended) HAProxy includes a built-in web dashboard that provides real-time metrics on the health of your backend servers, traffic volume, and error rates. To enable it, add a `listen` section to your configuration file:

listen stats
    bind *:8080
    stats enable
    stats uri /haproxy_stats
    stats refresh 10s
    stats auth admin:SecurePassword123!
*Note: You will need to open port 8080 in your firewall if you implement this (`sudo firewall-cmd –permanent –add-port=8080/tcp`).* ## Step 5: Validate and Start the Service Before starting HAProxy, it is crucial to validate the configuration file for syntax errors. HAProxy provides a command for this.

sudo haproxy -c -f /etc/haproxy/haproxy.cfg
If the output says `Configuration file is valid`, you can proceed to start and enable the service so it starts automatically on boot.

sudo systemctl start haproxy
sudo systemctl enable haproxy
Check the status to ensure it is running without errors:

sudo systemctl status haproxy
## Step 6: Verify the Load Balancing To test the deployment, open a web browser and navigate to the IP address of your HAProxy load balancer (e.g., `http://192.168.1.100`). To prove the traffic is being distributed, you can modify the default `index.html` file on each of your backend servers so they serve slightly different content (e.g., “Welcome to Web Node 01” and “Welcome to Web Node 02”). Refresh the page in your browser a few times. Due to the `roundrobin` algorithm, you should see the content alternate between Node 01 and Node 02, confirming that HAProxy is successfully distributing the incoming requests across your high-availability cluster.

Get the best tech tips delivered straight to your inbox.

Join thousands of readers mastering Apple, Google, Microsoft, and Linux.