How to install HAProxy on CentOS 7
HAProxy is a free HTTP/TCP high availability load balancer and proxy server. It spreads requests among multiple servers to mitigate issues resulting from single server failure. It is used by many well known highly trafficked websites such as Github, Stack Overflow and Reddit to improve uptime statistics.
Make sure that your CentOS 7 distribution is fully up to date.
yum -y update
You can install HAProxy from the default repositories.
yum -y install haproxy
Open the configuration file in a text editor.
The following is an example of a basic configuration for HTTP and HTTPS on two backend servers which are using the addresses 192.168.1.10 and 192.168.1.11. The “stats page” section is enabled in this example, which will allow you to better monitor the status of each individual proxy port.
log 127.0.0.1 local2
# turn on stats unix socket
stats socket /var/run/haproxy.cmd
option forwardfor except 127.0.0.0/8
timeout http-request 10s
timeout queue 1m
timeout connect 10s
timeout client 45s
timeout server 45s
timeout check 10s
listen stats :9000
stats uri /haproxy
stats realm HAProxy\ Statistics
stats auth haproxy:password
stats admin if TRUE
listen http :80
server web1 192.168.1.10:80 check inter 3000 rise 2 fall 3
server web2 192.168.1.11:80 check inter 3000 rise 2 fall 3
listen https :443
server web1 192.168.1.10:443 check inter 3000 rise 2 fall 3
server web2 192.168.1.11:443 check inter 3000 rise 2 fall 3
With the basic configuration above, you will be able to send traffic through ports 80 and 443 of both back-end web servers.
It will be necessary to restart HAProxy instance in order for it to reflect the changes made to the configuration file.
service haproxy restart
After restarting, visit the statistics URL to confirm that ports 80 and 443 are opened and traffic can flow through. Navigate to your proxy IP on port 9000 (for example, http://188.8.131.52:9000).
Once you’ve ensured that HAproxy is operating as intended, set it to start automatically on boot:
systemctl enable haproxy
If you wish to monitor your proxy status from the command line, you can install and open hatop.
tar xvf hatop-0.7.7.tar.gz
install -m 755 bin/hatop /usr/local/bin
hatop -s /var/run/haproxy.cmd
To avoid having to enter the -s parameter when calling hatop, insert the following line in your ~/.bashrc file:
echo "alias hatop='hatop -s /var/run/haproxy.cmd'" >> ~/.bashrc
Now that HAProxy is successfully installed and configured, you should notice improved performance and responsiveness in your web application. With careful monitoring and experimentation, you may discover ways to further adjust the load balancing in response to changed conditions in the future. If this guide was helpful to you, kindly share it with others who may also be interested.