Friday, January 6, 2012

How to install and configure HAProxy as an HTTP load balancer

# cd /usr/ports/net/haproxy ; make install

Check the following directories for further info:
documentation: '/usr/local/share/doc/haproxy'
examples: '/usr/local/share/examples/haproxy'

# ls /usr/local/share/examples/haproxy

# vim /usr/local/etc/haproxy.conf
maxconn 4096
pidfile /var/run/

mode http
retries 3
option redispatch
maxconn 2000
contimeout 5000
clitimeout 50000
srvtimeout 50000

listen YOUR_GROUP_NAME aaa.bbb.ccc.ddd:80
mode http
cookie GALAXY insert
balance roundrobin
option httpclose
option forwardfor
stats enable
stats auth myuser:mypass
server EARTH cookie MYGROUP_SERVER_01 check
server MOON cookie MYGROUP_SERVER_02 check

Note: aaa.bbb.ccc.ddd is your public IP address. or set it to

# echo 'haproxy_enable="YES"' >> /etc/rc.conf

# /usr/local/etc/rc.d/haproxy start

Go to See HAProxy Stats


In the configuration above, we used the port 8080 for the local/private Web servers. If these Web servers are running Nginx, you will need to include the following configuration in your http, server or location block (nginx.conf):

port_in_redirect off;

This is needed because if you try to reach this:

http://aaa.bbb.ccc.ddd/test (NO ending slash)

Then Nginx will try to redirect you there:


Which will obviously not work. So if you're running Nginx and that you decided to use a port different of 80, you will need this setting.

haproxy with multiple IP in one server

there are two things you can do. First, you can have as many "bind" lines as you want in a "listen" or "frontend" section. So if the only thing that changes is the IP, then it's the best thing to do. Second, if you have any reason to apply a different processing to each IP (eg: different ACLs, or rewrite rules), then you should use "frontend"+"backend" instead of "listen". A "listen" section is exactly a frontend plus a backend, both in the same section. By having multiple frontends, you can define what type of processing you want on each IP address, and make them all use the same backend (using the "default_backend" rule). And all your servers will only be placed in this single backend, with the same cookie name, same LB algorithm, same health checks, etc...

Hoping this helps, Willy


No comments: