Install and Setup HAProxy on CentOS 8

|
Last Updated:
|
|

This guide will walk you through how to install and setup HAProxy on CentOS 8. HAProxy is the current de-facto standard opensource load balancer. It offers high availability, load balancing and proxying for TCP and HTTP-based applications.

While offering load balancing, HAProxy supports different algorithms for load balancing. Some of the commonly used ones include;

  • Roundrobin – This is the default algorithm and it enables HAProxy to select each server to serve requests in turns according to their weights.
  • leastconn – The server with the lowest number of connections receives the connections. It is recommended where very long sessions are expected, such as LDAP, SQL.
  • source – With this algorithm, the source IP address is hashed and divided by the total weight of the running servers to designate which server will receive the request. This ensures that the same client IP address will always reach the same server as long as no server goes down or up. If the hash result changes due to the number of running servers changing, many clients will be directed to a different server.

Read more on HAProxy load balancing algorithms on the documentation page.

Install and Setup HAProxy on CentOS 8

For the purposes of demonstrating how HAProxy basically operates, this guide uses uses three virtual machines; one running as HAProxy load balancer and two others running web servers serving basic html pages.

Install HAProxy on CentOS 8

Run system update.

dnf update

After the system update is done, you can proceed to install HAProxy. HAProxy is available on the default CentOS 8 repos and the installation is as simple as running the command;

dnf install haproxy

Configuring HAProxy on CentOS 8

/etc/haproxy/haproxy.cfg is the default HAProxy configuration file. Below is a sample HAProxy default configuration file with no comments;

grep -v "^ *#" /etc/haproxy/haproxy.cfg | grep -v "^$"
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 *:5000
    acl url_static       path_beg       -i /static /images /javascript /stylesheets
    acl url_static       path_end       -i .jpg .gif .png .css .js
    use_backend static          if url_static
    default_backend             app
backend static
    balance     roundrobin
    server      static 127.0.0.1:4331 check
backend app
    balance     roundrobin
    server  app1 127.0.0.1:5001 check
    server  app2 127.0.0.1:5002 check
    server  app3 127.0.0.1:5003 check
    server  app4 127.0.0.1:5004 check

As you can see on the above configuration file, there are four HAProxy configuration sections;

  • The global settings which defines the parameters that apply to all servers running HAProxy
  • The default settings section defines the parameters that apply to all proxy subsections in a configuration (frontendbackend, and listen).
  • The frontend settings section defines the servers’ listening sockets for client connection requests. 
  • The backend settings section defines the real server IP addresses as well as the load balancer scheduling algorithm.
  • Sometimes, both backend and frontend can be combined under the listen section.

Read more about these sections on HAProxy essential sections.

Create a backup of the HAProxy configuration file.

cp /etc/haproxy/haproxy.cfg{,.old}

Defining Global HAProxy Settings

In our configuration, we will leave the default global settings as it.

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

Define HAProxy Default Settings

We will leave the default settings as is;

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

Defining HAProxy Frontend Settings

In this section, we will define how HAProxy is externally accessed to enable access to the backend servers. Since most options have been defined on defaults settings section, here is our frontend settings;

frontend lb01
    bind 192.168.56.133:80
    default_backend kifaruapps

Where;

  • bind defines an given IP address and port on which HAProxy listens on.
  • default_backend gives the name of a backend to send traffic to.

Defining HAProxy Backend Settings

On Backend section, define the real backend server IP addresses as well as the load balancer scheduling algorithm. 

backend kifaruapps
    balance roundrobin
    server webapp01  192.168.2.112:8080 check
    server webapp02  192.168.58.9:80 check
  • balance setting defines the roundrobin load balancer scheduling algorithm.
  • server setting specify the servers available in the back end.
  • check – enables health checks on the server. By default, a server is always considered available. If set, the server is available when accepting periodic TCP connections, to ensure that it is really able to serve requests.

Define HAProxy Listen Settings

You can optionally add the listen section to enable HAProxy statistics. HAProxy provides a dashboard called the HAProxy Stats page that displays the metrics related to the health of your servers, current request rates, response times, and more that gives a granular data on a per-frontend, backend, and server basis.

The Stats page can be enabled as shown below;

listen stats
    bind  192.168.56.133:8088       # Bind stats to port 8088
    log   global                    # Enable Logging
    stats enable                    # enable statistics reports 
    stats hide-version              # Hide the version of HAProxy
    stats refresh 30s               # HAProxy refresh time
    stats show-node                 # Shows the hostname of the node
    stats auth lbadmin:P@ssword     # Authentication for Stats page
    stats uri /lb_stats             # Statistics URL

Ensure that the stats port is allowed on firewall.

firewall-cmd --add-port=8088/tcp --permanent
firewall-cmd --reload

Be sure to check SELinux logs just in case anything is not accessible.

Finally, this is how our HAProxy configuration file is like;

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 lb01
    bind 192.168.56.133:80
    default_backend kifarunixapps    
backend kifarunixapps
    balance     roundrobin
    server webapp01  192.168.2.112:8080 check
    server webapp02  192.168.58.9:80 check
listen stats
    bind  192.168.56.133:8088       # Bind stats to port 8088
    stats enable                    # enable statistics reports  
    stats hide-version              # Hide the version of HAProxy
    stats refresh 30s               # HAProxy refresh time
    stats show-node                 # Shows the hostname of the node
    stats auth lbadmin:P@ssword     # Authentication for Stats page
    stats uri /lb_stats             # Statistics URL

Read more about the configuration options on HAProxy documentation page.

Verify HAProxy Configuration

To check HAProxy config file for any syntax errors, run the command below;

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

If all is well, you should get such an output;

Configuration file is valid

Open HAProxy port on firewall.

firewall-cmd --add-port=80/tcp --permanent
firewall-cmd --reload

Running HAProxy on CentOS 8

To start and enable HAProxy to run on system boot, run the command below;

systemctl enable --now haproxy

Check the status of HAProxy.

systemctl status haproxy
● haproxy.service - HAProxy Load Balancer
   Loaded: loaded (/usr/lib/systemd/system/haproxy.service; enabled; vendor preset: disabled)
   Active: active (running) since Thu 2020-03-05 22:34:58 EAT; 2s ago
  Process: 3262 ExecStartPre=/usr/sbin/haproxy -f $CONFIG -c -q (code=exited, status=0/SUCCESS)
 Main PID: 3263 (haproxy)
    Tasks: 2 (limit: 5047)
   Memory: 2.5M
   CGroup: /system.slice/haproxy.service
           ├─3263 /usr/sbin/haproxy -Ws -f /etc/haproxy/haproxy.cfg -p /run/haproxy.pid
           └─3265 /usr/sbin/haproxy -Ws -f /etc/haproxy/haproxy.cfg -p /run/haproxy.pid

Mar 05 22:34:58 ceph-admin.kifarunix-demo.com systemd[1]: Starting HAProxy Load Balancer...
Mar 05 22:34:58 ceph-admin.kifarunix-demo.com systemd[1]: Started HAProxy Load Balancer.

Configure HAProxy Logging on CentOS 8

To configure HAProxy standard logging edit /etc/rsyslog.conf and enable UDP syslog reception on port 514 by removing comments (#) on the lines, #module(load=”imudp”) and #input(type=”imudp” port=”514″) as shown below.

vim /etc/rsyslog.conf
...
# Provides UDP syslog reception
# for parameters see http://www.rsyslog.com/doc/imudp.html
module(load="imudp") # needs to be done just once
input(type="imudp" port="514")
...

Next, disable logging of private authentication messages sent to local2 facility, (local2.none) on /var/log/messages and enable logging on /var/log/haproxy.log as shown below.

...
*.info;mail.none;authpriv.none;cron.none,local2.none                /var/log/messages
local2.* /var/log/haproxy.log

Save the configuration file and run the command below to check for any errors.

rsyslogd -N1

Next, restart Rsyslog and HAProxy

systemctl restart rsyslog haproxy

You should now be able to have HAProxy logs on /var/log/haproxy.log.

tail -f /var/log/haproxy.log

Configure Apache X-Forwarded-For Logging on Backend Servers

Since we have configured HAProxy to add HTTP header “X-Forwarded-For” to all requests sent to the backend server (option forwardfor), you can configure logging for the same on the backend server. This ensures the IP address of the requesting client is captured instead of the HAProxy load balancer.

Therefore, login to the backend servers and configure Apache to log X-Forwarded-For headers. The default line we are changing is;

...
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
LogFormat "%h %l %u %t \"%r\" %>s %b" common
...

Hence, edit this line such that it looks like;

...
LogFormat "\"%{X-Forwarded-For}i\" %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
LogFormat "%h %l %u %t \"%r\" %>s %b" common
...

Save the file and run Apache configuration file syntax check command.

apachectl configtest
Syntax OK

Restart Apache

systemctl restart httpd

Testing HAProxy Load Balancer on CentOS 8

To verify that HAProxy is able to load balance the http requests, navigate to browser and access HAProxy using either the hostname or IP address.

Since it is using the roundrobin algorithm, when you refresh the page, you should be able to get content from both backend servers served.

webapp01
webapp02

Checking HAProxy Statistics

To check the statistics of your frontend and backend servers, simply navigate to stats url defined on the listen section; http://server-IP_OR_hostname:8088/lb_stats. Set the appropriate URL.

When prompted, authentication using the credentials defined by the stats auth on the listen section, in this demo, lbadmin:P@ssword, for username and password.

haproxy auth

HAProxy statistics

Install and Setup HAProxy on CentOS 8

That marks the end of our guide on how to install and setup HAProxy on CentOS 8.

Related Tutorials

Setup HAProxy Load Balancer on Fedora 30/Fedora 29

Configure HAProxy Load Balancer with SSL on Ubuntu 18.04/Debian 10/9

How to Install and Configure Pound as Apache HTTP Load balancer on Ubuntu 16.04

SUPPORT US VIA A VIRTUAL CUP OF COFFEE

We're passionate about sharing our knowledge and experiences with you through our blog. If you appreciate our efforts, consider buying us a virtual coffee. Your support keeps us motivated and enables us to continually improve, ensuring that we can provide you with the best content possible. Thank you for being a coffee-fueled champion of our work!

Photo of author
gen_too
Co-founder of Kifarunix.com, Linux Tips and Tutorials. Linux/Unix admin and author at Kifarunix.com.

2 thoughts on “Install and Setup HAProxy on CentOS 8”

Leave a Comment