Prerequisites

Basic Linux Command-line, Package Managment, Undestanding of Systemd, Networking fundamentals (tcp/ip ip DNS resolution Firewall concepts), Web Server Knowledge(http/https Apche nginx Node, virtual hosting concepts), SSl/TLS Basics

What is HAProxy Load Balancing?

HAProxy load balancing distributes incoming network traffic across multiple backend servers, ensuring optimal resource utilization, improved performance, and high availability. As a Layer 4 (TCP/UDP) and Layer 7 (HTTP/HTTPS) load balancer, HAProxy prevents server overload by intelligently routing requests using algorithms like round-robin, least connections, and IP hash. Moreover, HAProxy automatically detects failed servers and redirects traffic to healthy nodes, making it essential for production environments requiring 99.9%+ uptime.

Quick Start Command:

sudo apt install haproxy -y
sudo systemctl enable haproxy
sudo systemctl start haproxy

This guide demonstrates how to implement HAProxy load balancing with health checks, SSL termination, and failover capabilities for enterprise-grade infrastructure.


Table of Contents

  1. How Does HAProxy Load Balancing Work?
  2. What Are the Key Features of HAProxy?
  3. How to Install HAProxy on Linux
  4. How to Configure Basic Load Balancing
  5. What Load Balancing Algorithms Does HAProxy Support?
  6. How to Implement Health Checks
  7. How to Configure SSL/TLS Termination
  8. How to Set Up Session Persistence
  9. FAQ
  10. Troubleshooting Common Issues

How Does HAProxy Load Balancing Work?

HAProxy operates as a reverse proxy positioned between clients and backend servers. Consequently, when a client request arrives, HAProxy evaluates the current server load, applies the configured algorithm, and forwards the request to the optimal backend server. Furthermore, HAProxy continuously monitors backend server health through configurable health checks, automatically removing failed nodes from the rotation.

The load balancing process follows this workflow:

  1. Client Connection: Client initiates TCP/HTTP connection to HAProxy frontend
  2. Algorithm Selection: HAProxy applies the configured load balancing algorithm
  3. Backend Selection: Request is forwarded to the chosen backend server
  4. Health Verification: HAProxy confirms the selected backend is operational
  5. Response Handling: Server response is proxied back to the client
  6. Persistent Monitoring: Continuous health checks ensure backend availability

Additionally, HAProxy supports both Layer 4 (transport layer) and Layer 7 (application layer) load balancing. Layer 4 operates on IP addresses and ports, offering maximum performance, whereas Layer 7 makes routing decisions based on HTTP headers, URLs, and cookies, providing advanced traffic management capabilities.


What Are the Key Features of HAProxy?

HAProxy provides enterprise-grade load balancing features that distinguish it from alternative solutions. Therefore, understanding these capabilities helps you leverage HAProxy’s full potential:

Layer 4 and Layer 7 Load Balancing

HAProxy excels at both transport-layer (TCP/UDP) and application-layer (HTTP/HTTPS) traffic distribution. Specifically, Layer 4 load balancing delivers maximum throughput for generic TCP services, while Layer 7 enables content-based routing for web applications.

Advanced Load Balancing Algorithms

HAProxy supports multiple distribution algorithms including round-robin, least connections, source IP hashing, and URI-based routing. Subsequently, you can select the optimal algorithm for your specific use case.

SSL/TLS Termination

HAProxy offloads SSL/TLS encryption from backend servers, reducing computational overhead. As a result, backend servers focus on application logic while HAProxy handles cryptographic operations.

Health Monitoring and Failover

Continuous health checks detect backend failures within seconds. Consequently, HAProxy automatically removes unhealthy servers and redistributes traffic to operational nodes, ensuring uninterrupted service availability.

Session Persistence (Sticky Sessions)

HAProxy maintains client-server affinity through cookie-based or IP-based session persistence. Therefore, users consistently connect to the same backend server, essential for stateful applications.

External Reference: The HAProxy official documentation provides comprehensive feature descriptions and configuration examples.


How to Install HAProxy on Linux

Installing HAProxy varies slightly across distributions. Nevertheless, the process remains straightforward on all major Linux platforms.

Installation on Ubuntu/Debian

Ubuntu and Debian systems use the APT package manager for HAProxy installation:

# Update package repository
sudo apt update

# Install HAProxy
sudo apt install haproxy -y

# Verify installation
haproxy -v

Expected output shows HAProxy version information:

HAProxy version 2.8.5-1ubuntu3 2024/04/01

Installation on RHEL/CentOS/Rocky Linux

Red Hat-based distributions utilize YUM or DNF package managers:

# For RHEL/CentOS 7
sudo yum install haproxy -y

# For RHEL/Rocky Linux 8+
sudo dnf install haproxy -y

# Verify installation
haproxy -v

Installation from Source

Installing from source provides the latest features and customization options. However, this approach requires additional dependencies:

# Install build dependencies
sudo apt install build-essential libssl-dev libpcre3-dev zlib1g-dev -y

# Download HAProxy source
cd /usr/src
sudo wget https://www.haproxy.org/download/2.8/src/haproxy-2.8.5.tar.gz
sudo tar -xzf haproxy-2.8.5.tar.gz
cd haproxy-2.8.5

# Compile with SSL support
sudo make TARGET=linux-glibc USE_OPENSSL=1 USE_PCRE=1 USE_ZLIB=1

# Install binaries
sudo make install

# Verify installation
haproxy -v

Enable and Start HAProxy Service

After installation, enable HAProxy to start automatically at boot:

# Enable service at boot
sudo systemctl enable haproxy

# Start HAProxy service
sudo systemctl start haproxy

# Check service status
sudo systemctl status haproxy

Successful startup displays:

● haproxy.service - HAProxy Load Balancer
     Loaded: loaded (/lib/systemd/system/haproxy.service; enabled)
     Active: active (running)

How to Configure Basic Load Balancing

HAProxy configuration resides in /etc/haproxy/haproxy.cfg. Furthermore, the configuration file consists of four main sections: global settings, defaults, frontend definitions, and backend server pools.

Understanding HAProxy Configuration Structure

The configuration follows this hierarchy:

  • Global: Process-wide settings (logging, user, SSL)
  • Defaults: Default parameters for all sections
  • Frontend: Client-facing interface definitions
  • Backend: Server pool configurations

Creating a Basic Load Balancer Configuration

First, backup the default configuration:

sudo cp /etc/haproxy/haproxy.cfg /etc/haproxy/haproxy.cfg.backup

Next, create a basic load balancing configuration:

sudo nano /etc/haproxy/haproxy.cfg

Insert the following configuration:

global
    log /dev/log local0
    log /dev/log local1 notice
    chroot /var/lib/haproxy
    stats socket /run/haproxy/admin.sock mode 660 level admin
    stats timeout 30s
    user haproxy
    group haproxy
    daemon
    
    # SSL/TLS configuration
    ssl-default-bind-ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384
    ssl-default-bind-options no-sslv3 no-tlsv10 no-tlsv11

defaults
    log     global
    mode    http
    option  httplog
    option  dontlognull
    timeout connect 5000
    timeout client  50000
    timeout server  50000
    errorfile 400 /etc/haproxy/errors/400.http
    errorfile 403 /etc/haproxy/errors/403.http
    errorfile 408 /etc/haproxy/errors/408.http
    errorfile 500 /etc/haproxy/errors/500.http
    errorfile 502 /etc/haproxy/errors/502.http
    errorfile 503 /etc/haproxy/errors/503.http
    errorfile 504 /etc/haproxy/errors/504.http

# Frontend configuration - receives client connections
frontend web_frontend
    bind *:80
    bind *:443 ssl crt /etc/ssl/certs/haproxy.pem
    mode http
    default_backend web_backend
    
    # Optional: redirect HTTP to HTTPS
    redirect scheme https code 301 if !{ ssl_fc }

# Backend configuration - server pool
backend web_backend
    mode http
    balance roundrobin
    option httpchk GET /health
    
    # Backend servers
    server web1 192.168.1.101:8080 check inter 2000 rise 2 fall 3
    server web2 192.168.1.102:8080 check inter 2000 rise 2 fall 3
    server web3 192.168.1.103:8080 check inter 2000 rise 2 fall 3

# Statistics page
listen stats
    bind *:8404
    stats enable
    stats uri /stats
    stats refresh 30s
    stats auth admin:SecurePassword123

Configuration Parameter Explanation

The configuration includes several critical parameters:

  • *bind :80: Listen on all interfaces, port 80 (HTTP)
  • balance roundrobin: Use round-robin load balancing algorithm
  • option httpchk: Enable HTTP health checks
  • check: Enable health monitoring for backend server
  • inter 2000: Health check interval (2 seconds)
  • rise 2: Server considered operational after 2 successful checks
  • fall 3: Server marked down after 3 failed checks

Validating Configuration Syntax

Before applying changes, validate configuration syntax:

sudo haproxy -c -f /etc/haproxy/haproxy.cfg

Successful validation displays:

Configuration file is valid

Applying Configuration Changes

Reload HAProxy with the new configuration:

sudo systemctl reload haproxy

# Verify HAProxy is running
sudo systemctl status haproxy

Related Guide: Enhance your setup with Nginx reverse proxy configuration for complementary load balancing strategies.


What Load Balancing Algorithms Does HAProxy Support?

Selecting the appropriate load balancing algorithm significantly impacts application performance. Consequently, HAProxy offers multiple algorithms optimized for different scenarios.

Round Robin Algorithm

Round-robin distributes requests sequentially across backend servers. Therefore, each server receives equal request distribution over time.

Configuration:

backend web_backend
    balance roundrobin
    server web1 192.168.1.101:8080 check
    server web2 192.168.1.102:8080 check
    server web3 192.168.1.103:8080 check

Use Case: Applications with uniform request processing requirements and stateless sessions.

Advantages:

  • Simple and predictable distribution
  • Equal load across all servers
  • No algorithm overhead

Least Connections Algorithm

Least connections directs traffic to the server with fewest active connections. Subsequently, this prevents overloading busy servers.

Configuration:

backend web_backend
    balance leastconn
    server web1 192.168.1.101:8080 check
    server web2 192.168.1.102:8080 check
    server web3 192.168.1.103:8080 check

Use Case: Applications with varying request processing times, such as database queries or report generation.

Advantages:

  • Optimal for heterogeneous workloads
  • Prevents server overload
  • Dynamic load distribution

Source IP Hash Algorithm

Source IP hashing ensures clients consistently connect to the same backend server. As a result, this provides natural session persistence.

Configuration:

backend web_backend
    balance source
    hash-type consistent
    server web1 192.168.1.101:8080 check
    server web2 192.168.1.102:8080 check
    server web3 192.168.1.103:8080 check

Use Case: Stateful applications requiring session affinity without cookie-based persistence.

Advantages:

  • Natural session persistence
  • No cookie overhead
  • Consistent routing per client IP

URI-Based Load Balancing

URI hashing distributes requests based on the requested URI path. Consequently, similar requests route to the same backend server, improving cache efficiency.

Configuration:

backend web_backend
    balance uri
    hash-type consistent
    server web1 192.168.1.101:8080 check
    server web2 192.168.1.102:8080 check
    server web3 192.168.1.103:8080 check

Use Case: Content delivery networks or applications with path-specific caching requirements.

Weighted Round Robin

Weighted round-robin allows proportional traffic distribution based on server capacity. Therefore, powerful servers receive more connections.

Configuration:

backend web_backend
    balance roundrobin
    server web1 192.168.1.101:8080 weight 100 check
    server web2 192.168.1.102:8080 weight 50 check
    server web3 192.168.1.103:8080 weight 25 check

Use Case: Heterogeneous server environments with varying hardware capabilities.

External Resource: The HAProxy Configuration Manual provides detailed algorithm explanations and performance characteristics.


How to Implement Health Checks

Health checks ensure HAProxy routes traffic exclusively to operational backend servers. Moreover, configuring appropriate health check parameters prevents service disruptions during server failures.

HTTP Health Check Configuration

HTTP health checks verify backend server availability by requesting a specific URL:

backend web_backend
    mode http
    balance roundrobin
    option httpchk GET /health HTTP/1.1\r\nHost:\ example.com
    
    server web1 192.168.1.101:8080 check inter 2000 rise 2 fall 3
    server web2 192.168.1.102:8080 check inter 2000 rise 2 fall 3
    server web3 192.168.1.103:8080 check inter 2000 rise 2 fall 3

Health Check Parameters:

  • inter 2000: Check interval (2 seconds)
  • rise 2: Successful checks before marking server operational
  • fall 3: Failed checks before marking server down

TCP Health Check Configuration

TCP health checks verify port connectivity without HTTP protocol requirements:

backend database_backend
    mode tcp
    balance leastconn
    option tcp-check
    
    server db1 192.168.1.201:3306 check inter 3000 rise 2 fall 5
    server db2 192.168.1.202:3306 check inter 3000 rise 2 fall 5

Advanced Health Check with Expected Response

Verify specific HTTP response codes or content:

backend web_backend
    mode http
    option httpchk GET /health
    http-check expect status 200
    
    server web1 192.168.1.101:8080 check inter 2000
    server web2 192.168.1.102:8080 check inter 2000

Creating a Health Check Endpoint

Implement a lightweight health check endpoint on backend servers:

Node.js Example:

const express = require('express');
const app = express();

app.get('/health', (req, res) => {
    // Perform health checks (database, dependencies)
    const isHealthy = checkDatabaseConnection();
    
    if (isHealthy) {
        res.status(200).json({ status: 'healthy' });
    } else {
        res.status(503).json({ status: 'unhealthy' });
    }
});

app.listen(8080);

Monitoring Backend Server Status

Check backend server status through HAProxy stats page or command line:

# View backend server status
echo "show stat" | sudo socat stdio /run/haproxy/admin.sock | grep web_backend

# Disable specific backend server
echo "disable server web_backend/web1" | sudo socat stdio /run/haproxy/admin.sock

# Enable specific backend server
echo "enable server web_backend/web1" | sudo socat stdio /run/haproxy/admin.sock

Related Topic: Implement comprehensive monitoring with Prometheus and Grafana setup for HAProxy metrics.


How to Configure SSL/TLS Termination

SSL/TLS termination offloads encryption processing from backend servers to HAProxy. Consequently, backend servers handle only unencrypted traffic, improving overall performance.

Generating SSL Certificates

First, obtain SSL certificates from Let’s Encrypt or create self-signed certificates:

# Install Certbot
sudo apt install certbot -y

# Obtain Let's Encrypt certificate
sudo certbot certonly --standalone -d example.com -d www.example.com

# Combine certificate and private key
sudo cat /etc/letsencrypt/live/example.com/fullchain.pem \
         /etc/letsencrypt/live/example.com/privkey.pem \
         > /etc/ssl/certs/haproxy.pem

# Set appropriate permissions
sudo chmod 600 /etc/ssl/certs/haproxy.pem

Configuring SSL Termination

Enable SSL termination in the frontend configuration:

frontend https_frontend
    bind *:443 ssl crt /etc/ssl/certs/haproxy.pem
    mode http
    
    # Security headers
    http-response set-header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload"
    http-response set-header X-Frame-Options "SAMEORIGIN"
    http-response set-header X-Content-Type-Options "nosniff"
    http-response set-header X-XSS-Protection "1; mode=block"
    
    # Redirect HTTP to HTTPS
    redirect scheme https code 301 if !{ ssl_fc }
    
    default_backend web_backend

backend web_backend
    mode http
    balance roundrobin
    
    # Backend servers communicate over HTTP
    server web1 192.168.1.101:8080 check
    server web2 192.168.1.102:8080 check
    server web3 192.168.1.103:8080 check

Configuring Strong SSL/TLS Security

Enhance SSL security with modern cipher suites:

global
    # Modern SSL configuration
    ssl-default-bind-ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384
    ssl-default-bind-ciphersuites TLS_AES_128_GCM_SHA256:TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256
    ssl-default-bind-options ssl-min-ver TLSv1.2 no-tls-tickets
    
    tune.ssl.default-dh-param 2048

Automatic Certificate Renewal

Automate Let’s Encrypt certificate renewal:

# Create renewal script
sudo nano /usr/local/bin/renew-haproxy-cert.sh
#!/bin/bash
certbot renew --quiet --deploy-hook "cat /etc/letsencrypt/live/example.com/fullchain.pem \
                                          /etc/letsencrypt/live/example.com/privkey.pem \
                                          > /etc/ssl/certs/haproxy.pem && \
                                      systemctl reload haproxy"
# Make executable
sudo chmod +x /usr/local/bin/renew-haproxy-cert.sh

# Add to crontab
sudo crontab -e

Add the following line:

0 2 * * 1 /usr/local/bin/renew-haproxy-cert.sh

External Reference: Mozilla’s SSL Configuration Generator provides recommended SSL/TLS configurations for HAProxy.


How to Set Up Session Persistence

Session persistence ensures clients consistently connect to the same backend server. Therefore, stateful applications maintain user sessions without complex session sharing mechanisms.

Cookie-Based Session Persistence

HAProxy inserts cookies to track client-server affinity:

backend web_backend
    mode http
    balance roundrobin
    cookie SERVERID insert indirect nocache
    
    server web1 192.168.1.101:8080 check cookie web1
    server web2 192.168.1.102:8080 check cookie web2
    server web3 192.168.1.103:8080 check cookie web3

Cookie Parameters:

  • insert: HAProxy inserts the cookie
  • indirect: Cookie not sent to backend servers
  • nocache: Prevent caching of responses with cookies

Source IP-Based Persistence

Alternatively, use source IP hashing for persistence:

backend web_backend
    mode http
    balance source
    hash-type consistent
    
    server web1 192.168.1.101:8080 check
    server web2 192.168.1.102:8080 check
    server web3 192.168.1.103:8080 check

Application Session Persistence

For applications with existing session management, preserve backend cookies:

backend web_backend
    mode http
    balance roundrobin
    cookie JSESSIONID prefix nocache
    
    server web1 192.168.1.101:8080 check cookie web1
    server web2 192.168.1.102:8080 check cookie web2
    server web3 192.168.1.103:8080 check cookie web3

Testing Session Persistence

Verify session persistence behavior:

# Test with curl
curl -c cookies.txt -b cookies.txt http://example.com
curl -c cookies.txt -b cookies.txt http://example.com

# Check assigned server in cookies
cat cookies.txt | grep SERVERID

FAQ

What is the difference between HAProxy and Nginx load balancing?

HAProxy specializes in Layer 4 and Layer 7 load balancing with advanced health checks and failover capabilities. Conversely, Nginx functions primarily as a web server with integrated load balancing features. HAProxy offers superior load balancing algorithms and monitoring, whereas Nginx provides better static content serving. For dedicated load balancing, HAProxy delivers superior performance and features.

How many backend servers can HAProxy handle?

HAProxy scales to thousands of backend servers in a single configuration. However, practical limits depend on available system resources (CPU, memory, network bandwidth). Production deployments commonly support 100-500 backend servers per HAProxy instance. For larger deployments, implement multiple HAProxy instances with DNS-based load balancing or VRRP failover.

Does HAProxy support WebSocket connections?

Yes, HAProxy fully supports WebSocket connections through proper configuration. Configure the frontend and backend with appropriate timeout values:

frontend websocket_frontend
    bind *:80
    timeout client 1h
    default_backend websocket_backend

backend websocket_backend
    timeout server 1h
    timeout tunnel 1h
    server ws1 192.168.1.101:8080 check

How do I monitor HAProxy performance?

HAProxy provides multiple monitoring mechanisms: the built-in statistics page, socket commands, and Prometheus exporter. Access the stats page by browsing to http://your-server:8404/stats. Additionally, integrate with monitoring tools like Prometheus, Grafana, or Datadog for comprehensive performance visibility.

Can HAProxy perform SSL passthrough?

Yes, HAProxy supports SSL passthrough, allowing encrypted traffic to reach backend servers without decryption. Configure TCP mode with SNI routing:

frontend https_frontend
    bind *:443
    mode tcp
    tcp-request inspect-delay 5s
    tcp-request content accept if { req_ssl_hello_type 1 }
    use_backend web_backend

backend web_backend
    mode tcp
    server web1 192.168.1.101:443 check

What are the system requirements for HAProxy?

HAProxy runs efficiently on minimal resources. A basic load balancer requires 1 CPU core, 512MB RAM, and 10GB disk space. However, production environments handling significant traffic benefit from 4+ CPU cores, 8GB+ RAM, and fast network interfaces. Memory requirements scale with connection counts and SSL termination load.

How do I implement rate limiting in HAProxy?

HAProxy provides connection rate limiting through stick tables:

frontend web_frontend
    bind *:80
    stick-table type ip size 100k expire 30s store conn_rate(3s)
    tcp-request connection track-sc0 src
    tcp-request connection reject if { sc_conn_rate(0) gt 10 }
    default_backend web_backend

This configuration limits each IP address to 10 connections per 3 seconds.

What logging options does HAProxy provide?

HAProxy logs to syslog by default. Configure detailed HTTP logging:

global
    log /dev/log local0 info

defaults
    log global
    option httplog
    option log-separate-errors

View logs with:

sudo tail -f /var/log/haproxy.log

Troubleshooting Common Issues

Backend Servers Marked as Down

When HAProxy marks backend servers as down, investigate health check failures:

Diagnostic Steps:

  1. Verify backend server connectivity:
# Test TCP connectivity
telnet 192.168.1.101 8080

# Test HTTP endpoint
curl -I http://192.168.1.101:8080/health
  1. Check HAProxy logs:
sudo tail -f /var/log/haproxy.log | grep "server.*is DOWN"
  1. Examine health check configuration:
# View current backend status
echo "show stat" | sudo socat stdio /run/haproxy/admin.sock | grep web_backend
  1. Adjust health check parameters:
backend web_backend
    option httpchk GET /health
    # Increase tolerance for slow responses
    server web1 192.168.1.101:8080 check inter 5000 rise 3 fall 5

SSL Certificate Errors

SSL certificate issues prevent secure connections:

Common Solutions:

  1. Verify certificate file permissions:
sudo ls -la /etc/ssl/certs/haproxy.pem
sudo chmod 600 /etc/ssl/certs/haproxy.pem
  1. Validate certificate format:
# Certificate should contain both cert and private key
sudo openssl x509 -in /etc/ssl/certs/haproxy.pem -text -noout
  1. Test SSL configuration:
# Check SSL binding
sudo haproxy -c -f /etc/haproxy/haproxy.cfg
  1. Verify certificate chain:
openssl s_client -connect example.com:443 -showcerts

High Connection Timeouts

Connection timeouts indicate capacity or configuration issues:

Troubleshooting Approach:

  1. Increase timeout values:
defaults
    timeout connect 10000
    timeout client  60000
    timeout server  60000
  1. Check system limits:
# Verify file descriptor limits
ulimit -n

# Increase if necessary
sudo nano /etc/security/limits.conf

Add:

haproxy soft nofile 65535
haproxy hard nofile 65535
  1. Monitor connection statistics:
# View real-time connection count
watch -n 1 'echo "show info" | sudo socat stdio /run/haproxy/admin.sock | grep Curr'
  1. Enable connection queueing:
backend web_backend
    balance roundrobin
    maxconn 5000
    server web1 192.168.1.101:8080 check maxconn 1000

Performance Degradation

Performance issues require systematic analysis:

Diagnostic Process:

  1. Monitor CPU and memory usage:
# Check HAProxy resource consumption
top -p $(pgrep haproxy)

# Detailed process statistics
ps aux | grep haproxy
  1. Analyze backend response times:
# Enable timing information in logs
echo "show stat" | sudo socat stdio /run/haproxy/admin.sock | awk -F',' '{print $1, $2, $10}'
  1. Review load balancing algorithm:
# Switch to least connections for better distribution
backend web_backend
    balance leastconn
  1. Implement connection limits:
backend web_backend
    balance roundrobin
    server web1 192.168.1.101:8080 check maxconn 500
    server web2 192.168.1.102:8080 check maxconn 500

Configuration Syntax Errors

Configuration errors prevent HAProxy from starting:

Resolution Steps:

  1. Validate configuration syntax:
sudo haproxy -c -f /etc/haproxy/haproxy.cfg
  1. Check for common syntax errors:
# Verify indentation (use spaces, not tabs)
cat -A /etc/haproxy/haproxy.cfg | grep -E '^\s*\t'

# Look for missing colons or brackets
grep -n "backend\|frontend" /etc/haproxy/haproxy.cfg
  1. Review systemd service logs:
sudo journalctl -u haproxy -n 50 --no-pager
  1. Test configuration incrementally:
# Start with minimal configuration
sudo cp /etc/haproxy/haproxy.cfg /etc/haproxy/haproxy.cfg.complex
sudo nano /etc/haproxy/haproxy.cfg
# Add sections one at a time, testing after each addition

Session Persistence Not Working

Session persistence failures cause users to lose session state:

Troubleshooting Methods:

  1. Verify cookie configuration:
# Test cookie insertion
curl -c cookies.txt http://example.com
cat cookies.txt | grep SERVERID
  1. Check backend server cookie handling:
backend web_backend
    cookie SERVERID insert indirect nocache httponly secure
    server web1 192.168.1.101:8080 check cookie web1
  1. Enable cookie debugging:
defaults
    option httplog
    # Capture cookies in logs
    capture cookie SERVERID len 32
  1. Verify client supports cookies:
# Test with curl
curl -v -c cookies.txt -b cookies.txt http://example.com

Related Troubleshooting: Reference Linux network troubleshooting guide for connectivity issues.


Additional Resources

Official Documentation and Standards

Community Resources and Tools

Related LinuxTips.pro Articles

Performance and Security Tools


Author’s Note: HAProxy load balancing represents a critical component of modern high-availability infrastructure. By implementing proper health checks, SSL termination, and session persistence, you ensure resilient, performant applications. Consequently, investing time in proper HAProxy configuration delivers significant operational benefits, including improved uptime, scalability, and user experience. As systems grow in complexity, HAProxy remains an essential tool for traffic management and failover capabilities.

Publication Series: This article is part of the Linux Mastery 100 series, providing comprehensive coverage of essential Linux administration topics from beginner fundamentals to advanced enterprise deployments.

Mark as Complete

Did you find this guide helpful? Track your progress by marking it as completed.