RHEL BasedRocky Linux

How To Install HAProxy on Rocky Linux 9

Install HAProxy on Rocky Linux 9

In this tutorial, we will show you how to install HAProxy on Rocky Linux 9. HAProxy stands as one of the most reliable open-source solutions for load balancing and high availability in today’s complex infrastructure environments. As organizations continue to scale their applications across multiple servers, proper load balancing becomes not just beneficial but essential. Rocky Linux 9, a robust and enterprise-ready CentOS alternative, provides an excellent platform for deploying HAProxy. This comprehensive guide walks you through the complete process of installing, configuring, and optimizing HAProxy on Rocky Linux 9, ensuring your systems achieve maximum reliability and performance.

Table of Contents

Understanding HAProxy

HAProxy (High Availability Proxy) is a powerful, open-source solution designed to provide high availability, load balancing, and proxying for TCP and HTTP-based applications. First released in 2006, it has become the go-to load balancing solution for many high-traffic websites and critical infrastructure deployments.

What is HAProxy?

HAProxy functions primarily as a load balancer and proxying solution that can distribute client requests across multiple servers. Unlike simpler load balancers, HAProxy operates at both Layer 4 (transport layer) and Layer 7 (application layer) of the OSI model, allowing for sophisticated traffic management based on not just network parameters but also application-specific attributes.

Key Features of HAProxy

HAProxy comes packed with an impressive array of capabilities that make it stand out in the load balancing landscape:

  • Advanced Layer 4 (TCP) and Layer 7 (HTTP/HTTPS) load balancing
  • Efficient SSL/TLS termination, offloading encryption processing from backend servers
  • Robust health checking mechanisms that detect server failures
  • Sticky sessions to maintain user connections to specific servers
  • Detailed logging and real-time statistics for monitoring and troubleshooting
  • Content switching based on URL patterns or other HTTP attributes
  • Connection pooling to reduce backend server load
  • Rate limiting to protect against traffic spikes
  • Dynamic configuration with zero downtime reloads
  • Multithreaded architecture for optimal performance on multi-core systems

Use Cases for HAProxy

The versatility of HAProxy makes it suitable for numerous scenarios:

  • Web application load balancing to distribute traffic across multiple web servers
  • API gateway implementations to manage microservices architectures
  • Database load balancing for improved performance and redundancy
  • SSL/TLS termination point to centralize certificate management
  • High availability setups for critical services
  • Traffic rate limiting and DDoS protection
  • Blue/green deployments and A/B testing environments

Prerequisites

Before diving into the installation process, ensure your environment meets the necessary requirements for a successful HAProxy deployment.

System Requirements

For optimal performance of HAProxy on Rocky Linux 9, your system should meet these specifications:

  • CPU: Minimum 2 cores (4+ cores recommended for production environments)
  • RAM: At least 2GB (4GB or more recommended for busy environments)
  • Storage: Minimum 20GB for the operating system and logs
  • Network: Stable network connection with appropriate bandwidth for expected traffic

Network Setup

Planning your network architecture is crucial before deployment. Consider:

  • Dedicated IP addresses for HAProxy frontend services
  • Network segmentation between client-facing and backend networks
  • Appropriate subnet configuration to facilitate communication between all components
  • DNS resolution for hostname-based routing (if applicable)

Required Access

To complete this installation, you’ll need:

  • Root or sudo privileges on the Rocky Linux 9 system
  • Network access to package repositories
  • Firewall permissions to configure necessary ports

Knowledge Prerequisites

A basic understanding of the following concepts will be helpful:

  • Linux command line operations
  • Networking fundamentals including IP addressing and ports
  • Text editing in Linux (vim, nano, etc.)
  • Basic HTTP/HTTPS protocol concepts

Lab Environment Setup

To effectively demonstrate HAProxy installation and configuration, let’s establish a practical lab environment.

Sample Architecture

Our example setup will consist of:

  • 1 HAProxy load balancer node (haproxy.example.com – 192.168.1.10)
  • 2 Web server nodes (web1.example.com – 192.168.1.21, web2.example.com – 192.168.1.22)

Node Configuration

Each node in our architecture needs proper configuration. Start by setting appropriate hostnames:


# On HAProxy node
sudo hostnamectl set-hostname haproxy.example.com

# On web server nodes
sudo hostnamectl set-hostname web1.example.com  # First web server
sudo hostnamectl set-hostname web2.example.com  # Second web server

Host File Configuration

Update the /etc/hosts file on each server to ensure proper name resolution:

sudo nano /etc/hosts

Add the following entries to all nodes:

192.168.1.10 haproxy.example.com haproxy
192.168.1.21 web1.example.com web1
192.168.1.22 web2.example.com web2

Network Verification

Confirm connectivity between all nodes using the ping command:

ping -c 4 haproxy.example.com
ping -c 4 web1.example.com
ping -c 4 web2.example.com

Successful ping responses indicate proper network connectivity between your servers.

Step 1: System Preparation

Proper system preparation ensures a stable foundation for your HAProxy installation.

Updating the System

Begin by updating your Rocky Linux 9 system to ensure all packages are current:

sudo dnf update -y

This command updates the package database and installs all available updates. The `-y` flag automatically answers “yes” to confirmation prompts.

Verifying System Status

After updates, check system status to confirm all services are running properly:

sudo systemctl status

Address any issues before proceeding with the installation.

Setting Static IP

For production environments, configure a static IP address to prevent connectivity issues due to changing IPs:

sudo nano /etc/sysconfig/network-scripts/ifcfg-enp0s3

Modify the network interface configuration (replace enp0s3 with your actual interface name):

BOOTPROTO=static
IPADDR=192.168.1.10
NETMASK=255.255.255.0
GATEWAY=192.168.1.1
DNS1=8.8.8.8
DNS2=8.8.4.4
ONBOOT=yes

Apply the network changes:


sudo systemctl restart NetworkManager

Configuring Firewall

Configure the firewall to allow HAProxy traffic. For our setup, we’ll open port 80 (HTTP) and port 443 (HTTPS):

sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --reload

For the statistics page (if you plan to use it):

sudo firewall-cmd --permanent --add-port=8404/tcp
sudo firewall-cmd --reload

SELinux Considerations

If SELinux is enabled (recommended for security), configure it to allow HAProxy to function properly:

sudo setsebool -P haproxy_connect_any 1

This permits HAProxy to connect to any port, which is necessary for its proxy functionality.

Step 2: Installing HAProxy

With the system prepared, we can now proceed with the actual installation of HAProxy.

Repository Information

First, check the available HAProxy version in the default repositories:

sudo dnf info haproxy

The default Rocky Linux repositories typically include a stable but possibly older version of HAProxy. For the latest version, you might need to enable additional repositories.

Installation Command

Install HAProxy using the following command:

sudo dnf install haproxy -y

This command installs HAProxy along with its dependencies from the configured repositories.

Dependency Resolution

During installation, DNF automatically resolves and installs all required dependencies. These typically include various libraries needed for HAProxy functionality.

Verification of Installation

After installation completes, verify that HAProxy was installed correctly:

haproxy -v

This command displays the installed HAProxy version and build information. You should see output similar to:

HAProxy version 2.4.x

Package Information

For detailed information about the installed package:

sudo dnf info haproxy

This shows package version, size, repository source, and other metadata.

Installation Troubleshooting

If you encounter issues during installation:

  • Check system connectivity to repositories with ping dl.fedoraproject.org
  • Verify disk space with df -h
  • Examine the DNF logs at /var/log/dnf.log
  • Try clearing the DNF cache with sudo dnf clean all and retry installation

Step 3: Understanding the HAProxy Configuration File

Before making changes, it’s essential to understand the HAProxy configuration structure.

Configuration File Location

The main HAProxy configuration file is located at:

/etc/haproxy/haproxy.cfg

Backing Up the Default Configuration

Always create a backup before modifying the configuration:

sudo cp /etc/haproxy/haproxy.cfg /etc/haproxy/haproxy.cfg.original

This backup allows you to revert to the default configuration if needed.

Configuration File Structure

The HAProxy configuration file is organized into several key sections:

  1. Global Section: System-wide settings affecting all HAProxy processes, including process management, security, and performance options.
  2. Default Section: Default parameters applied to all frontend and backend sections unless overridden.
  3. Frontend Section: Defines how requests are received and routed to backends, including binding addresses, ports, and routing rules.
  4. Backend Section: Defines groups of servers that will receive forwarded requests, including server addresses, health checks, and load balancing methods.

Key Parameters Explained

Let’s examine some critical configuration parameters:

  • maxconn: Maximum number of concurrent connections HAProxy can handle
  • mode: Operating mode (http or tcp)
  • timeout: Various timeout settings for connections
  • option httplog: Enables HTTP request logging
  • balance: The load balancing algorithm (roundrobin, leastconn, etc.)
  • server: Defines backend server addresses and parameters

Configuration Syntax

HAProxy configuration follows a specific syntax:

section_name section_label
    parameter value
    parameter value

For example:

frontend http_front
    bind *:80
    default_backend http_back

Configuration errors can prevent HAProxy from starting, so careful attention to syntax is crucial.

Step 4: Basic HAProxy Configuration

Now let’s create a basic configuration for load balancing HTTP traffic.

Global Settings

Edit the configuration file:

sudo nano /etc/haproxy/haproxy.cfg

Start with the global section:

global
    log /dev/log local0
    log /dev/log local1 notice
    chroot /var/lib/haproxy
    stats socket /var/lib/haproxy/stats
    stats timeout 30s
    user haproxy
    group haproxy
    daemon
    
    # Default SSL material locations
    ca-base /etc/ssl/certs
    crt-base /etc/ssl/private
    
    # Default ciphers to use
    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

Default Settings

Configure the defaults section:

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

Add a frontend section to handle incoming HTTP requests:

frontend http_front
    bind *:80
    stats uri /haproxy?stats
    default_backend http_back

This configuration:

  • Binds HAProxy to all network interfaces on port 80
  • Provides a statistics URL at /haproxy?stats
  • Routes all traffic to the http_back backend by default

Backend Configuration

Configure a backend for your web servers:

backend http_back
    balance roundrobin
    option httpchk HEAD / HTTP/1.1\r\nHost:\ localhost
    server web1 192.168.1.21:80 check
    server web2 192.168.1.22:80 check

This backend configuration:

  • Uses the roundrobin algorithm to distribute requests evenly
  • Implements health checks on the root path (/)
  • Defines two backend servers with their IP addresses and ports
  • Enables health checking for each server

Example Configuration

Here’s the complete basic configuration:

global
    log /dev/log local0
    log /dev/log local1 notice
    chroot /var/lib/haproxy
    stats socket /var/lib/haproxy/stats
    stats timeout 30s
    user haproxy
    group haproxy
    daemon
    ca-base /etc/ssl/certs
    crt-base /etc/ssl/private
    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

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 http_front
    bind *:80
    stats uri /haproxy?stats
    default_backend http_back

backend http_back
    balance roundrobin
    option httpchk HEAD / HTTP/1.1\r\nHost:\ localhost
    server web1 192.168.1.21:80 check
    server web2 192.168.1.22:80 check

Validating Configuration

Always validate the configuration before applying it:

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

If the configuration is valid, you’ll see:

Configuration file is valid

If there are errors, the output will indicate the specific issues to address.

Step 5: Advanced Configuration Options

Once you have a basic configuration working, consider these advanced options to enhance your HAProxy setup.

SSL/TLS Termination

To enable SSL/TLS termination, first generate or obtain SSL certificates, then configure HAProxy:

frontend https_front
    bind *:443 ssl crt /etc/ssl/certs/haproxy.pem
    reqadd X-Forwarded-Proto:\ https
    default_backend http_back

Generate a combined certificate file (replacing with your actual certificate paths):

sudo cat /path/to/your/certificate.crt /path/to/your/private.key > /etc/ssl/certs/haproxy.pem
sudo chmod 600 /etc/ssl/certs/haproxy.pem

ACLs (Access Control Lists)

Implement conditional routing with ACLs:

frontend http_front
    bind *:80
    acl is_api path_beg /api
    use_backend api_back if is_api
    default_backend web_back

This configuration routes requests beginning with /api to a dedicated backend.

Sticky Sessions

Maintain user sessions on specific servers:

backend http_back
    balance roundrobin
    cookie SERVERID insert indirect nocache
    server web1 192.168.1.21:80 check cookie server1
    server web2 192.168.1.22:80 check cookie server2

This configuration uses cookies to maintain client connections to the same backend server.

HTTP Compression

Enable compression to save bandwidth:

frontend http_front
    bind *:80
    compression algo gzip
    compression type text/html text/plain text/css application/javascript
    default_backend http_back

Custom Error Pages

Configure custom error pages for a better user experience:

backend http_back
    balance roundrobin
    errorfile 503 /etc/haproxy/errors/custom_503.http
    server web1 192.168.1.21:80 check
    server web2 192.168.1.22:80 check

Create your custom error file at the specified path.

Rate Limiting

Implement basic rate limiting to protect your servers:

frontend http_front
    bind *:80
    stick-table type ip size 100k expire 30s store http_req_rate(10s)
    acl too_many_requests sc0_http_req_rate gt 20
    http-request deny if too_many_requests
    default_backend http_back

This configuration tracks client IP addresses and denies requests exceeding 20 per 10-second period.

Monitoring and Statistics

Set up an enhanced statistics page:

listen stats
    bind *:8404
    stats enable
    stats uri /stats
    stats refresh 30s
    stats admin if LOCALHOST
    stats auth admin:password

This creates a dedicated statistics interface on port 8404, protected by basic authentication.

Step 6: Starting and Managing HAProxy Service

Now that you’ve configured HAProxy, it’s time to manage the service.

Starting HAProxy

Start the HAProxy service with:

sudo systemctl start haproxy

Enabling Automatic Start

To ensure HAProxy starts automatically after system reboots:

sudo systemctl enable haproxy

Checking Service Status

Verify that HAProxy is running correctly:

sudo systemctl status haproxy

Look for “active (running)” in the output, which indicates the service is operational.

Reloading Configuration

After making configuration changes, reload HAProxy without downtime:

sudo systemctl reload haproxy

This gracefully reloads the configuration while maintaining existing connections.

Stopping the Service

If you need to stop HAProxy:

sudo systemctl stop haproxy

Service Logs

Monitor HAProxy operations through its logs:

sudo journalctl -u haproxy

For real-time log monitoring:

sudo journalctl -u haproxy -f

Step 7: Testing the HAProxy Setup

After configuration, thoroughly test your HAProxy deployment to ensure it’s working as expected.

Basic Connectivity Testing

Verify that HAProxy is accepting connections:

curl -I http://haproxy.example.com

You should receive an HTTP response header from one of your backend servers.

Load Balancing Verification

Confirm that requests are being distributed across backend servers:

for i in {1..10}; do curl -s http://haproxy.example.com | grep "Server"; done

If you’ve configured your backend servers to display their hostname, this command should show requests being distributed across different servers.

Health Check Testing

Test the health check functionality by temporarily stopping one backend server:

# On one web server
sudo systemctl stop nginx  # or apache2, depending on your web server

Check the HAProxy stats page to confirm the server is marked as down, and verify that traffic is routing only to the healthy server.

Performance Testing

Conduct basic performance testing with a tool like ab (Apache Benchmark):

ab -n 1000 -c 10 http://haproxy.example.com/

This sends 1000 requests with 10 concurrent connections, providing basic performance metrics.

Simulating Failures

Test high availability by simulating server failures:

  1. Start with all servers running
  2. Stop a backend server
  3. Verify traffic continues to other servers
  4. Restart the stopped server
  5. Confirm it rejoins the pool after passing health checks

Monitoring Connections

Access the statistics page you configured (e.g., http://haproxy.example.com:8404/stats) to monitor:

  • Current connections
  • Server health status
  • Request rates
  • Error counts
  • Session distribution

Security Considerations

Implementing proper security measures is essential for any production HAProxy deployment.

Securing the Admin Interface

Protect your statistics page with strong authentication and IP restrictions:

listen stats
    bind *:8404
    stats enable
    stats uri /stats
    stats refresh 30s
    stats auth admin:StrongPassword123!
    acl local src 127.0.0.1/32 192.168.1.0/24
    stats admin if local

This configuration restricts admin access to localhost and your local network.

Implementing Firewall Rules

Restrict access to the HAProxy server using firewall rules:

sudo firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="192.168.1.0/24" service name="http" accept'
sudo firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="192.168.1.0/24" service name="https" accept'
sudo firewall-cmd --reload

This allows HTTP/HTTPS access only from your local network.

TLS Best Practices

Implement modern TLS security practices:

frontend https_front
    bind *:443 ssl crt /etc/ssl/certs/haproxy.pem alpn h2,http/1.1
    http-response set-header Strict-Transport-Security max-age=15768000
    ssl-default-bind-options no-sslv3 no-tlsv10 no-tlsv11
    ssl-default-bind-ciphersuites TLS_AES_128_GCM_SHA256:TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256

This configuration:

  • Enables HTTP/2
  • Implements HSTS for enhanced security
  • Disables older, vulnerable TLS versions
  • Uses strong cipher suites

Regular Updates

Establish a system for regular updates:

sudo dnf update haproxy -y

Consider setting up automated security updates for critical components.

Logging and Monitoring

Configure comprehensive logging for security monitoring:

global
    log /dev/log local0 info
    log /dev/log local1 notice

Consider forwarding logs to a centralized log management system for analysis.

Troubleshooting Common Issues

Even with careful planning, issues can arise. Here are solutions to common problems.

Configuration Problems

If HAProxy fails to start due to configuration errors:

  1. Check the syntax with sudo haproxy -c -f /etc/haproxy/haproxy.cfg
  2. Review logs with sudo journalctl -u haproxy
  3. Common errors include:
    • Incorrect indentation
    • Missing sections
    • Invalid parameters
    • Duplicate frontend/backend names

Connection Issues

If clients cannot connect to HAProxy:

  1. Verify HAProxy is running: sudo systemctl status haproxy
  2. Check firewall settings: sudo firewall-cmd --list-all
  3. Test local connectivity: curl -I http://localhost
  4. Examine bind address configuration (ensure it’s binding to the correct interface)

Backend Server Failures

If backends are being marked as down unexpectedly:

  1. Review health check settings
  2. Verify backend server functionality directly
  3. Check network connectivity between HAProxy and backends
  4. Examine backend server logs for errors
  5. Adjust health check thresholds if needed

Performance Bottlenecks

For performance issues:

  1. Increase maxconn values in global and frontend sections
  2. Enable HTTP keepalives to reduce connection overhead
  3. Consider enabling multithreading for multi-core servers
  4. Implement caching where appropriate
  5. Monitor CPU and memory usage

Log Analysis

Use logs to diagnose issues:

sudo grep haproxy /var/log/messages
sudo journalctl -u haproxy --since today

Look for patterns in error messages and request handling to identify recurring problems.

Real-World Examples

Let’s examine some practical HAProxy configurations for common scenarios.

Web Application Load Balancing

A complete configuration for web application load balancing:

frontend web_front
    bind *:80
    bind *:443 ssl crt /etc/ssl/certs/combined.pem
    http-request redirect scheme https unless { ssl_fc }
    acl host_app1 hdr(host) -i app1.example.com
    acl host_app2 hdr(host) -i app2.example.com
    use_backend app1_back if host_app1
    use_backend app2_back if host_app2
    default_backend default_back

backend app1_back
    balance roundrobin
    option httpchk GET /health HTTP/1.1\r\nHost:\ app1.example.com
    server app1a 192.168.1.31:8080 check
    server app1b 192.168.1.32:8080 check

backend app2_back
    balance roundrobin
    option httpchk GET /health HTTP/1.1\r\nHost:\ app2.example.com
    server app2a 192.168.1.33:8080 check
    server app2b 192.168.1.34:8080 check

backend default_back
    balance roundrobin
    server default 192.168.1.35:8080 check

This configuration handles SSL termination, HTTP-to-HTTPS redirection, and hostname-based routing to different backend applications.

API Gateway Setup

HAProxy as an API gateway:

frontend api_gateway
    bind *:443 ssl crt /etc/ssl/certs/api.pem
    
    # Rate limiting
    stick-table type ip size 200k expire 10m store http_req_rate(10s)
    acl too_many_reqs sc0_http_req_rate gt 100
    http-request deny if too_many_reqs
    
    # JWT validation
    acl valid_jwt var(txn.auth_valid) -m bool
    http-request deny unless valid_jwt
    
    # API routing
    acl path_users path_beg /api/users
    acl path_products path_beg /api/products
    
    use_backend users_api if path_users
    use_backend products_api if path_products

backend users_api
    balance roundrobin
    server users1 192.168.1.41:8000 check
    server users2 192.168.1.42:8000 check

backend products_api
    balance roundrobin
    server products1 192.168.1.43:8000 check
    server products2 192.168.1.44:8000 check

This example implements API gateway functionality with rate limiting, authentication verification, and path-based routing.

Microservices Architecture

HAProxy for microservices:

frontend microservices_front
    bind *:80
    bind *:443 ssl crt /etc/ssl/certs/services.pem
    
    acl auth_service path_beg /auth
    acl user_service path_beg /users
    acl order_service path_beg /orders
    acl product_service path_beg /products
    
    use_backend auth_back if auth_service
    use_backend user_back if user_service
    use_backend order_back if order_service
    use_backend product_back if product_service

backend auth_back
    balance roundrobin
    server auth1 192.168.1.51:8000 check
    server auth2 192.168.1.52:8000 check

backend user_back
    balance roundrobin
    server user1 192.168.1.53:8000 check
    server user2 192.168.1.54:8000 check

backend order_back
    balance roundrobin
    server order1 192.168.1.55:8000 check
    server order2 192.168.1.56:8000 check

backend product_back
    balance roundrobin
    server product1 192.168.1.57:8000 check
    server product2 192.168.1.58:8000 check

This configuration routes traffic to different microservices based on the request path.

Congratulations! You have successfully installed HAProxy. Thanks for using this tutorial for installing the HAProxy high-performance TCP/HTTP load balancer on your Rocky Linux 9 system. For additional help or useful information, we recommend you check the official HAProxy website.

VPS Manage Service Offer
If you don’t have time to do all of this stuff, or if this is not your area of expertise, we offer a service to do “VPS Manage Service Offer”, starting from $10 (Paypal payment). Please contact us to get the best deal!

r00t

r00t is an experienced Linux enthusiast and technical writer with a passion for open-source software. With years of hands-on experience in various Linux distributions, r00t has developed a deep understanding of the Linux ecosystem and its powerful tools. He holds certifications in SCE and has contributed to several open-source projects. r00t is dedicated to sharing her knowledge and expertise through well-researched and informative articles, helping others navigate the world of Linux with confidence.
Back to top button