How to setup load balancer with haproxy on Ubuntu server 14.04

Install haproxy first

sudo apt-get install haproxy

Make backup copy of default haproxy.cfg

sudo cp /etc/haproxy/haproxy.cfg /etc/haproxy/haproxy.cfg.backup
sudo nano /etc/haproxy/haproxy.cfg

Configure your haproxy.cfg

global
log /dev/log local0
log /dev/log local1 notice
chroot /var/lib/haproxy
user haproxy
group haproxy
daemon

defaults
log global
mode http
option httplog
option dontlognull
contimeout 5000
clitimeout 50000
srvtimeout 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

listen webcluster *:80
mode http
stats enable
stats auth kim:mypassword
balance roundrobin
option httpchk HEAD / HTTP/1.0
option forwardfor
cookie LSW_WEB insert
option httpclose
server web01 192.168.1.33:80 cookie WEB01 check
server web02 192.168.1.34:80 cookie WEB02 check
server web03 192.168.1.xx:80 cookie WEB03 check

For sticky sessions use the following for the pool

server web01 192.168.1.191:80 cookie WEB01 check
server web02 192.168.1.192:80 cookie WEB02 check
server web03 192.168.1.xxx:80 cookie WEB03 check

For static websites without session use the following format

server web01 192.168.1.191:80 check
server web02 192.168.1.192:80 check
server web03 192.168.1.xxx:80 check

 

Enable HAproxy by editing the /etc/default/haproxy

sudo nano /etc/default/haproxy
# Set ENABLED to 1 if you want the init script to start haproxy.
ENABLED=1
# Add extra flags here.
#EXTRAOPTS="-de -m 16"

Start haproxy service

sudo service haproxy start

Test your load balancer and its stats

http://your.ip.address/haproxy?stats

Fix your webserver logging as they are no longer serving directly to users. From
Users -> webserver
Users -> Haproxy -> webserver

sudo nano /etc/apache2/apache2.conf

Change below

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

to

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

Leave a Reply

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

Scroll to top