This example assumes that firewall and selinux is disabled. We are going to use the following three servers.
Apache1: 192.168.124.2 apache1.example.com
Apache2: 192.168.124.3 apache2.example.com
HAProxy: 192.168.124.10 haproxy.example.com
All three servers should be able to reach each other. Enter the following in the /etc/hosts file in all three nodes
192.168.124.2 apache1.example.com apache1
192.168.124.3 apache2.example.com apache2
192.168.124.10 haproxy.example.com haproxy
Now install apache service on the two apache nodes using the following command
#yum install httpd -y
Create a sample HTML file in the apache nodes in differentiate them and start the httpd service
#systemctl start httpd.service
Install and enable Epel repository on the haproxy node
#yum install epel-release -y
Install HA proxy
#yum install haproxy -y
The default configuration file haproxy.cfg is located in /etc/haproxy/
Lets make a backup of the original file
#cd /etc/haproxy
#cp haproxy.cfg haproxy.cfg.bkp
Now lets edit the configuration file. We need to clear the existing frontend/backend config and create our own config
Delete the following lines in haproxy.cfg
------------------------------------------------------------------------
frontend main *: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
------------------------------------------------------------------------
Now add the following lines
-------------------------------------------------------------------------
#webapp1 is the name we give for our frontend
frontend webapp1
#Makes the haproxy service listen on port number 80
bind *:80
#defining the backen name
default_backend webapp1_servers
#send X-Forwarded-For header
option forwardfor
#Backend configuration
backend webapp1_servers
#Load balencing protocol
balance roundrobin
server apache1 192.168.124.89:80 check
server apache2 192.168.124.51:80 check
-------------------------------------------------------------------------
Note: The X-Forwarded-For request header helps you identify the IP address of a client when you use an HTTP or HTTPS load balancer. Because load balancers intercept traffic between clients and servers, your server access logs contain only the IP address of the load balancer.
Save the config file and restart haproxy service
#systemctl restart haproxy.service
Now hit the haprosy node's IP address in the browser and it should direct us to one of the web servers.