Blog / Linux/ Install and Configure HAProxy as a Layer 4 TCP Load Balancer on CentOS 7

Install and Configure HAProxy as a Layer 4 TCP Load Balancer on CentOS 7

centos 7 安装HAproxy四层TCP负载均衡配置及测试

Introduction

This guide explains how to install and configure HAProxy as a Layer 4 TCP load balancer on CentOS 7, including basic testing. Note: The HAProxy version used (1.8.12) is outdated; it is recommended to use a newer stable version for production environments.

Environment and Architecture

Assume the following network setup:

  • HAProxy Load Balancer IP: 166.110.110.100
  • Backend Server 1 IP: 166.110.110.1
  • Backend Server 2 IP: 166.110.110.2

System Preparation

Before installing HAProxy, perform these system configurations (suitable for testing; adjust for production based on security policies).

Disable SELinux

# Edit the SELinux configuration file
vi /etc/selinux/config
# Change SELINUX=enforcing to:
SELINUX=disabled
# Save, exit, and run this command for immediate effect (permanent after reboot)
setenforce 0

Disable Firewall (For Testing Only)

# Stop and disable the firewalld service
systemctl stop firewalld.service
systemctl disable firewalld.service

Install HAProxy

These steps compile and install HAProxy 1.8.12 from source.

# Install tools and download source
yum install wget gcc -y
wget -c --no-check-certificate https://src.fedoraproject.org/repo/pkgs/haproxy/haproxy-1.8.12.tar.gz
tar -xvf haproxy-1.8.12.tar.gz
cd haproxy-1.8.12

# Create HAProxy user and group
groupadd haproxy
useradd -g haproxy haproxy -s /bin/false

# Compile and install
make TARGET=linux2628 USE_OPENSSL=1 USE_ZLIB=1 USE_PCRE=1
make install PREFIX=/usr/local/haproxy

# Create config directory and copy config file
mkdir -p /etc/haproxy
cp examples/haproxy.cfg /etc/haproxy/

# Create necessary directories and set permissions
mkdir -p /var/lib/haproxy
chown -R haproxy:haproxy /var/lib/haproxy

Configure HAProxy

Edit the configuration file /etc/haproxy/haproxy.cfg to set up a Layer 4 TCP load balancer.

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

defaults
    mode                    tcp          # Set to TCP mode for Layer 4
    log                     global
    option                  tcplog       # Use TCP log format
    option                  dontlognull
    option                  redispatch
    retries                 3
    timeout connect         10s
    timeout client          1m
    timeout server          1m
    maxconn                 3000

# Admin statistics page (optional, for monitoring)
listen admin_stats
    bind 127.0.0.1:1080
    mode http
    stats enable
    stats hide-version
    stats uri /stats
    stats refresh 30s
    stats realm HAProxy Statistics
    stats auth admin:admin

# Main TCP load balancer configuration
listen web_tcp_frontend
    bind 0.0.0.0:80
    mode tcp
    balance leastconn          # Use least connections algorithm
    server s1 166.110.110.1:80 check
    server s2 166.110.110.2:80 check

Service Management

Create a Systemd service file for management. Create /usr/lib/systemd/system/haproxy.service:

[Unit]
Description=HAProxy Load Balancer
After=network.target

[Service]
ExecStart=/usr/local/haproxy/sbin/haproxy -f /etc/haproxy/haproxy.cfg
ExecReload=/bin/kill -USR2 $MAINPID
Restart=on-failure

[Install]
WantedBy=multi-user.target

Then use systemctl to manage the service:

# Reload systemd configuration
systemctl daemon-reload
# Start HAProxy
systemctl start haproxy.service
# Enable auto-start on boot
systemctl enable haproxy.service
# Check status
systemctl status haproxy.service
# Other commands: stop, restart, reload

The admin statistics page is accessible at http://166.110.110.100:1080/stats (username/password: admin/admin).

Backend Service Setup and Testing

To test load balancing, deploy a simple web service on the two backend servers. This example uses lighttpd.

Backend Server Configuration

On each backend server (166.110.110.1 and 166.110.110.2), execute:

# 1. Disable firewall and SELinux (for testing)
systemctl stop firewalld.service
systemctl disable firewalld.service
# Edit /etc/selinux/config, set SELINUX=disabled, and run setenforce 0

# 2. Install lighttpd
yum install -y epel-release lighttpd

# 3. (Optional) Edit config to disable IPv6
vi /etc/lighttpd/lighttpd.conf
# Find server.use-ipv6 and set to "disable"

# 4. Start and enable the service
systemctl start lighttpd.service
systemctl enable lighttpd.service

Create Test Pages

To differentiate the backend servers, modify their default index pages:

  • On Server 1 (166.110.110.1):
    echo "

    This is Upstream Server 1

    " > /var/www/lighttpd/index.html
  • On Server 2 (166.110.110.2):
    echo "

    This is Upstream Server 2

    " > /var/www/lighttpd/index.html

Test Load Balancing

From a client, use a browser or curl to repeatedly access the HAProxy server's IP:

curl http://166.110.110.100

Refreshing multiple times should show responses alternating between "This is Upstream Server 1" and "This is Upstream Server 2" (depending on the configured load balancing algorithm), confirming that load balancing is working.

HAProxy Load Balancing Algorithms

HAProxy supports multiple algorithms, specified with the balance directive. Common ones include:

  • roundrobin: Weighted round-robin, dynamic adjustment, most common.
  • static-rr: Weighted round-robin with static, fixed weights.
  • leastconn: Forwards requests to the backend with the fewest current connections; ideal for long-lived connections.
  • source: Hashes the source IP; requests from the same IP go to the same backend, useful for session persistence.
  • uri: Hashes the left part of the URI (before the question mark) to direct the same resource to a fixed backend.
  • url_param: Uses url_param <name> to hash based on a specified URL parameter value.
  • hdr(name): Hashes based on a specified HTTP header field.
  • rdp-cookie(name): Hashes based on RDP Cookie for TCP-layer session persistence.

For Layer 4 TCP load balancing, leastconn and source are commonly used.

Post a Comment

Your email will not be published. Required fields are marked with *.