DEV Community

Janak Shrestha
Janak Shrestha

Posted on

Install and Configure HaProxy LBR

There is a static website running in Stratos Datacenter. They have already configured the app servers and code is already deployed there. To make it work properly, they need to configure LBR server. There are number of options for that, but team has decided to go with HAproxy. FYI, apache is running on port 8087 on all app servers. Complete this task as per below details.

a. Install and configure HAproxy on LBR server using yum only and make sure all app servers are added to HAproxy load balancer. HAproxy must serve on default http port (Note: Please do not remove stats socket /var/lib/haproxy/stats entry from haproxy default config.).

b. Once done, you can access the website using curl http://localhost:80 on the LBR server.


Introduction

Load balancing is a critical component of modern infrastructure, ensuring high availability, scalability, and reliability for web applications. HAProxy (High Availability Proxy) is one of the most popular open-source load balancers, known for its performance, reliability, and rich feature set. It is widely used in production environments to distribute traffic across multiple backend servers.

This guide covers the complete process of installing and configuring HAProxy on a load balancer server to distribute traffic to multiple application servers running Apache. The tutorial is based on a real-world scenario where a static website needed to be load balanced across three app servers in a datacenter environment.


Understanding HAProxy

What is HAProxy

HAProxy is a free, open-source software that provides high availability load balancing and proxying for TCP and HTTP-based applications. It is written in C and is known for its high performance, reliability, and low resource consumption.

Key Features

HAProxy offers several features that make it ideal for production environments. It supports layer 4 (TCP) and layer 7 (HTTP) load balancing. Various load balancing algorithms are available, including round-robin, least connections, and source IP hash. Health checks ensure traffic is only sent to healthy backend servers. SSL/TLS termination and session persistence are supported. A statistics interface provides real-time monitoring.

HAProxy Architecture

HAProxy acts as an intermediary between clients and backend servers. Clients connect to HAProxy, which then forwards requests to one of the available backend servers based on the configured load balancing algorithm.

Component Description
Frontend Defines how requests are received
Backend Defines the servers that will handle requests
Listen Combines frontend and backend in one section
Global Process-wide settings
Defaults Default parameters for all sections

Prerequisites

Before beginning, ensure the following are available:

  • Access to the load balancer server (stlb01) with root or sudo privileges
  • App servers configured and running Apache on port 8087
  • Network connectivity between the LBR server and app servers
  • Basic understanding of Linux networking and web servers

Server Details for This Tutorial

Detail Value
LBR Server stlb01
User loki
Password Mischi3f
App Server 1 stapp01 (Apache on port 8087)
App Server 2 stapp02 (Apache on port 8087)
App Server 3 stapp03 (Apache on port 8087)
HAProxy Port 80

Installing HAProxy

Connect to the load balancer server and switch to root.

ssh loki@stlb01
sudo su -
Enter fullscreen mode Exit fullscreen mode

Install HAProxy using the system package manager.

yum install -y haproxy
Enter fullscreen mode Exit fullscreen mode

The installation includes HAProxy and its dependencies.


Understanding the Default Configuration

The default HAProxy configuration file is located at /etc/haproxy/haproxy.cfg. It contains global settings, defaults, a frontend, and a backend.

cat /etc/haproxy/haproxy.cfg
Enter fullscreen mode Exit fullscreen mode

The default configuration includes a stats socket at /var/lib/haproxy/stats which must be preserved. It also includes default frontend and backend sections that need to be modified.


Configuring HAProxy

Step 1: Backup the Original Configuration

Always backup the original configuration before making changes.

cp /etc/haproxy/haproxy.cfg /etc/haproxy/haproxy.cfg.bak
Enter fullscreen mode Exit fullscreen mode

Step 2: Edit the Configuration File

Edit the configuration file to add the correct frontend and backend sections.

vi /etc/haproxy/haproxy.cfg
Enter fullscreen mode Exit fullscreen mode

Step 3: Complete Configuration

Replace the configuration with the following content.

#---------------------------------------------------------------------
# Global settings
#---------------------------------------------------------------------
global
    log         127.0.0.1 local2
    chroot      /var/lib/haproxy
    pidfile     /var/run/haproxy.pid
    maxconn     4000
    user        haproxy
    group       haproxy
    daemon
    stats socket /var/lib/haproxy/stats
    ssl-default-bind-ciphers PROFILE=SYSTEM
    ssl-default-server-ciphers PROFILE=SYSTEM

#---------------------------------------------------------------------
# common defaults
#---------------------------------------------------------------------
defaults
    mode                    http
    log                     global
    option                  httplog
    option                  dontlognull
    option http-server-close
    option forwardfor       except 127.0.0.0/8
    option                  redispatch
    retries                 3
    timeout http-request    10s
    timeout queue           1m
    timeout connect         10s
    timeout client          1m
    timeout server          1m
    timeout http-keep-alive 10s
    timeout check           10s
    maxconn                 3000

#---------------------------------------------------------------------
# Main frontend
#---------------------------------------------------------------------
frontend main
    bind *:80
    default_backend app

#---------------------------------------------------------------------
# Backend for app servers
#---------------------------------------------------------------------
backend app
    balance roundrobin
    server stapp01 stapp01:8087 check
    server stapp02 stapp02:8087 check
    server stapp03 stapp03:8087 check
Enter fullscreen mode Exit fullscreen mode

Step 4: Configuration Explanation

Section Parameter Description
global stats socket Unix socket for stats (must be preserved)
defaults mode http Operate in HTTP mode
defaults timeout Various timeout settings
frontend bind *:80 Listen on all interfaces on port 80
frontend default_backend Send traffic to backend named app
backend balance roundrobin Use round-robin load balancing
backend server Define backend servers with health checks

Verifying the Configuration

Before restarting HAProxy, verify the configuration is valid.

haproxy -c -f /etc/haproxy/haproxy.cfg
Enter fullscreen mode Exit fullscreen mode

Expected output:

Configuration file is valid
Enter fullscreen mode Exit fullscreen mode

Starting and Enabling HAProxy

Start the HAProxy service and enable it to start on boot.

systemctl start haproxy
systemctl enable haproxy
systemctl status haproxy
Enter fullscreen mode Exit fullscreen mode

The status output should show the service is active and running.


Verifying the Setup

Check Listening Ports

ss -tlnp | grep :80
Enter fullscreen mode Exit fullscreen mode

Expected output shows HAProxy listening on port 80.

LISTEN 0 3000 0.0.0.0:80 0.0.0.0:* users:(("haproxy",pid=59036,fd=7))
Enter fullscreen mode Exit fullscreen mode

Test with Curl

curl http://localhost:80
Enter fullscreen mode Exit fullscreen mode

Expected output:

Welcome to xFusionCorp Industries!
Enter fullscreen mode Exit fullscreen mode

Test Round-Robin Load Balancing

Run multiple curl commands to verify traffic is distributed across all backend servers.

for i in {1..6}; do curl -s http://localhost:80; echo; done
Enter fullscreen mode Exit fullscreen mode

Check Backend Health

Test each backend server directly to ensure they are reachable.

curl -I http://stapp01:8087
curl -I http://stapp02:8087
curl -I http://stapp03:8087
Enter fullscreen mode Exit fullscreen mode

Expected output shows HTTP 200 OK for each server.


Troubleshooting Common Issues

503 Service Unavailable

When HAProxy returns a 503 error, it means no backend server is available. This typically indicates that HAProxy cannot reach the backend servers.

Cause 1: Incorrect IP Addresses or Hostnames

If the backend servers are configured with wrong IP addresses or hostnames that don't resolve, HAProxy cannot connect.

Fix: Use hostnames that resolve correctly.

# Check if hostnames resolve
getent hosts stapp01
getent hosts stapp02
getent hosts stapp03

# Update configuration to use hostnames
backend app
    balance roundrobin
    server stapp01 stapp01:8087 check
    server stapp02 stapp02:8087 check
    server stapp03 stapp03:8087 check
Enter fullscreen mode Exit fullscreen mode

Cause 2: Backend Servers Not Running

If Apache is not running on the app servers, HAProxy cannot connect.

Fix: Start Apache on each app server.

ssh tony@stapp01
sudo systemctl start httpd
sudo systemctl enable httpd
Enter fullscreen mode Exit fullscreen mode

Cause 3: Firewall Blocking Connections

If a firewall is blocking port 8087 on the app servers, HAProxy cannot connect.

Fix: Allow port 8087 on each app server.

sudo firewall-cmd --zone=public --add-port=8087/tcp --permanent
sudo firewall-cmd --reload
Enter fullscreen mode Exit fullscreen mode

Configuration File Errors

When HAProxy fails to start, check the configuration syntax.

haproxy -c -f /etc/haproxy/haproxy.cfg
Enter fullscreen mode Exit fullscreen mode

Common errors include duplicate section names, invalid syntax, or missing parameters.

Duplicate Section Names

HAProxy does not allow duplicate frontend or backend names. Ensure each section has a unique name.

# Check for duplicates
grep -n "^frontend\|^backend" /etc/haproxy/haproxy.cfg
Enter fullscreen mode Exit fullscreen mode

Port Already in Use

If port 80 is already in use by another service, HAProxy fails to start.

ss -tlnp | grep :80
Enter fullscreen mode Exit fullscreen mode

Identify and stop the conflicting service.

Checking Logs

HAProxy logs can be checked using journalctl.

journalctl -u haproxy -n 50
Enter fullscreen mode Exit fullscreen mode

Best Practices

Always Backup Configuration

Before making changes, back up the configuration file.

cp /etc/haproxy/haproxy.cfg /etc/haproxy/haproxy.cfg.bak
Enter fullscreen mode Exit fullscreen mode

Preserve the Stats Socket

The stats socket at /var/lib/haproxy/stats is used for monitoring and management. Do not remove this entry.

stats socket /var/lib/haproxy/stats
Enter fullscreen mode Exit fullscreen mode

Use Health Checks

Always configure health checks to ensure traffic is only sent to healthy servers.

server stapp01 stapp01:8087 check
Enter fullscreen mode Exit fullscreen mode

Test Configuration Before Restart

Always verify the configuration before restarting the service.

haproxy -c -f /etc/haproxy/haproxy.cfg
Enter fullscreen mode Exit fullscreen mode

Monitor Backend Health

Use the HAProxy stats interface to monitor backend health.

echo "show stat" | socat stdio /var/lib/haproxy/stats
Enter fullscreen mode Exit fullscreen mode

Document Configuration Changes

Maintain documentation of configuration changes for auditing and troubleshooting.


Automation Script

#!/bin/bash

echo "Installing and Configuring HAProxy"
echo "==================================="

# Install HAProxy
yum install -y haproxy

# Backup original configuration
cp /etc/haproxy/haproxy.cfg /etc/haproxy/haproxy.cfg.bak

# Write new configuration
cat > /etc/haproxy/haproxy.cfg << 'EOF'
global
    log         127.0.0.1 local2
    chroot      /var/lib/haproxy
    pidfile     /var/run/haproxy.pid
    maxconn     4000
    user        haproxy
    group       haproxy
    daemon
    stats socket /var/lib/haproxy/stats
    ssl-default-bind-ciphers PROFILE=SYSTEM
    ssl-default-server-ciphers PROFILE=SYSTEM

defaults
    mode                    http
    log                     global
    option                  httplog
    option                  dontlognull
    option http-server-close
    option forwardfor       except 127.0.0.0/8
    option                  redispatch
    retries                 3
    timeout http-request    10s
    timeout queue           1m
    timeout connect         10s
    timeout client          1m
    timeout server          1m
    timeout http-keep-alive 10s
    timeout check           10s
    maxconn                 3000

frontend main
    bind *:80
    default_backend app

backend app
    balance roundrobin
    server stapp01 stapp01:8087 check
    server stapp02 stapp02:8087 check
    server stapp03 stapp03:8087 check
EOF

# Verify configuration
haproxy -c -f /etc/haproxy/haproxy.cfg

# Start and enable HAProxy
systemctl start haproxy
systemctl enable haproxy

# Verify
systemctl status haproxy
ss -tlnp | grep :80
curl http://localhost:80
Enter fullscreen mode Exit fullscreen mode

Conclusion

Summary of the Setup

HAProxy has been successfully installed and configured on the load balancer server. The frontend listens on port 80 and distributes traffic to three backend app servers running Apache on port 8087. The round-robin algorithm ensures even distribution of requests. Health checks ensure traffic is only sent to healthy servers.

Key Takeaways

HAProxy is a powerful and efficient load balancer for HTTP and TCP applications. The stats socket at /var/lib/haproxy/stats must be preserved. Backend servers should be referenced by hostnames or reachable IP addresses. Health checks are essential for ensuring high availability. Configuration should always be verified before restarting the service.

Verification Results

Check Result
Configuration valid Yes
Service active Yes
Listening on port 80 Yes
Backend servers reachable Yes
Website accessible Yes

Final Configuration

frontend main
    bind *:80
    default_backend app

backend app
    balance roundrobin
    server stapp01 stapp01:8087 check
    server stapp02 stapp02:8087 check
    server stapp03 stapp03:8087 check
Enter fullscreen mode Exit fullscreen mode

Additional Resources

Manual Pages

  • man haproxy - HAProxy documentation
  • man haproxy.cfg - Configuration file reference
  • man socat - Socket cat for stats

Related Topics

  • HAProxy ACLs and content switching
  • SSL/TLS termination with HAProxy
  • Session persistence and stick tables
  • HAProxy statistics and monitoring
  • High availability with keepalived

Useful Commands

Command Purpose
haproxy -c -f /etc/haproxy/haproxy.cfg Verify configuration
systemctl status haproxy Check service status
`ss -tlnp \ grep :80`
curl http://localhost:80 Test the load balancer
`echo "show stat" \ socat stdio /var/lib/haproxy/stats`

Top comments (0)