How to Setup HAProxy as Load Balancer for Nginx in CentOS 7

Filed Under: UNIX/Linux

Written in C by Willy Tarreau, HAProxy, also known as High Availability Proxy is a fast and lightweight HTTP load balancer and proxy server. It has a low CPU usage and is occasioned by a small memory footprint. The load balancer is used by popular websites such as StackOverflow, Twitter, Github, and Tumblr to mention just but a few.

In this guide, we will show you how to set up HAProxy as a load balancer for Nginx web server on CentOS 7. The load balancer will sit in front of 2 Nginx web servers and equitably distribute HTTP requests to the servers.

HAProxy Balance Algorithm

This is the algorithm used by the load balancer for selection of the web servers when distributing workloads.

1. Roundrobin

This is the simplest of the algorithms. Basically, each new connection will be handled by the next web server. For instance, if you have 4 back-end servers, Each of them will handle requests in succession. When the last web server on the list is reached, the load balancer will start from the top again with the first web server.

2. Lastconn

Here a new request will be handled by the server with the least number of connections. This comes in handy when load and times of requests differ by great variations.

Getting started

To start off, perform a pre-flight checklist and ensure that you have the following.

1. CentOS 7 servers

Hostname Server IP address
load-balancer 173.82.168.96
web-server-1 173.82.2.236
web-server-2 173.82.94.57

2. SSH access to all the servers

Below is a graphical representation of the setup.

HAProxy Load Balancer

Step 1: Configure /etc/hosts file in the load balancer

Log in to the load balancer using SSH and add the Nginx web servers IP addresses and hostnames as shown.

vim /etc/hosts


173.82.2.236    web-server-1

173.82.94.57    web-server-2

Edit Etc Hosts File

Save and exit vim text editor.

Next, log into each of the Web servers (web-server-1 and web-server-2) and edit the /etc/hosts file to point to the load balancer.


173.82.168.96   load-balancer

Save and exit the text editor.

Step 2: Install and configure HAProxy on load balancer server

The HAProxy repository is readily available on the CentOS repository. To install and set up HAProxy, first, log in and update the system repositories.

 yum update -y

Next, install HAProxy using the command:

yum -y install haproxy

Sample Output

set up  Haproxy

Once the installation is successful and complete, head out to the haproxy directory.

cd /etc/haproxy

Backup the haproxy.cfg file by renaming it to haproxy.cfg.bak

mv haproxy.cfg  haproxy.cfg.bak

Next, create a new HAproxy configuration file.

vim haproxy.cfg


#---------------------------------------------------------------------
# Global settings
#---------------------------------------------------------------------
global
    log         127.0.0.1 local2     #Log configuration

    chroot      /var/lib/haproxy
    pidfile     /var/run/haproxy.pid
    maxconn     4000
    user        haproxy             #Haproxy running under user and group "haproxy"
    group       haproxy
    daemon

    # turn on stats unix socket
    stats socket /var/lib/haproxy/stats

#---------------------------------------------------------------------
# common defaults that all the 'listen' and 'backend' sections will
# use if not designated in their block
#---------------------------------------------------------------------
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

#---------------------------------------------------------------------
#HAProxy Monitoring Config
#---------------------------------------------------------------------
listen haproxy3-monitoring *:8080                #Haproxy Monitoring run on port 8080
    mode http
    option forwardfor
    option httpclose
    stats enable
    stats show-legends
    stats refresh 5s
    stats uri /stats                             #URL for HAProxy monitoring
    stats realm Haproxy\ Statistics
    stats auth Password123: Password123            #User and Password for login to the monitoring dashboard
    stats admin if TRUE
    default_backend app-main                    #This is optionally for monitoring backend

#---------------------------------------------------------------------
# FrontEnd Configuration
#---------------------------------------------------------------------
frontend main
    bind *:80
    option http-server-close
    option forwardfor
    default_backend app-main

#---------------------------------------------------------------------
# BackEnd round robin as balance algorithm
#---------------------------------------------------------------------
backend app-main
    balance roundrobin                                     #Balance algorithm
    option httpchk HEAD / HTTP/1.1\r\nHost:\ localhost    #Check the server application is up and healty - 200 status code
    server web-server-1 173.82.2.236:80 check                 #Nginx1
    server web-server-2 173.82.94.57:80 check                 #Nginx2

Take note of the web servers which have been specified in the last 2 lines as shown in the output.

Save and exit the text editor.

Next, We are going to configure the rsyslog daemon to log the HAProxy statistics.

Edit the rsyslog.conf file to enable the UDP port 514 to be used by rsyslog.

vim /etc/rsyslog.conf

To allow UDP connection via port 154, uncomment the following lines.


$ModLoad imudp
$UDPServerRun 514

Enable UDP Coonection To Rsyslog

Save and exit the text editor.

Next, create a new HAProxy configuration file for syslog.

vim  /etc/rsyslog.d/haproxy.conf

Paste the following configuration


local2.=info     /var/log/haproxy-access.log    #For Access Log
local2.notice    /var/log/haproxy-info.log      #For Service Info - Backend, loadbalancer

Save and exit the text editor.

Proceed and restart rsyslog.

systemctl restart rsyslog

Next, start and enable Haproxy to start at boot up.


systemctl start haproxy
systemctl enable haproxy

Start And Enable Haproxy

To confirm that HaProxy is up and running, execute:

systemctl status haproxy

Check Haproxy Status

In the next step, we are going to install Nginx to our web servers.

Step 3: Installing and configuring Nginx

The only crucial step remaining is the installation of Nginx on each of our web servers.

But first, install EPEL repository as shown

yum install epel-release

Next, install Nginx

yum install nginx -y

Sample output

Install Nginx

With Nginx installed on both servers, we are going to modify the index.html files in each of the Nginx web servers in order to create a distinction between each server when simulating with the HAproxy load balancer.

Move to the html directory as shown:

cd /usr/share/nginx/html/

Backup the index.html file

mv index.html index.html.bak

Next, create a new index.html file and paste some sample content.

For Web Server 1

echo "web-server-1. Hey ! This is your first web server" > index.html 

For Web Server 2

echo "web-server-2. Hey ! This is your second web server" > index.html 

Next, start Nginx in both web servers and confirm if the service is running


systemctl start  nginx
systemctl status nginx

Start Nginx And Check Status

Testing Load balancing

To verify that everything went well, run the following command repeatedly.

curl 173.82.168.96

Your output should be similar to this.

Curl Command To Test HAProxy

As you can observe keenly, with each subsequent run on the curl command, the output alternates between the first and the second web server content Perfect!

Now, let’s try testing using the web browser.

http://load-balancer-IP-address

This will display the content on either of the web servers, In this case, web-server-2.

Load Balancer Web Server 2

Now, try refreshing once or twice and the output will point to the other web server, in this case, web-server-1.

Load Balancer Web Server 1

Awesome! This confirms that our load balancer is able to equitably distribute HTTP requests between our web servers.

TO gather more statistics of the load balancer browser the following URL

http://load-balancer-IP:8080/stats

Use the Password123 as the username and Password as we defined in haproxy.cfg configuration file.

Load Balancer Stats

This sums up this tutorial on how to set up HAProxy load balancer for Nginx on CentOS 7. Feel free to try it out and share this guide on your social networks. As always, your feedback will be appreciated.

Comments

  1. min maung says:

    very good explanation

Leave a Reply

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

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages