I’ve been playing around with deploying REST web services via Jersey with embedded Jetty servers and decided to use HAProxy as a software load balancer in my development environment as there aren’t any spare F5 appliances lying around.

After downloading the tar, issue the following commands to quickly install HAProxy in your current directory:

$ tar xvfz haproxy-1.4.22.tar.gz
$ cd haproxy-1.4.22
$ sudo make install

Before we start on the configuration file, let’s assume that we have the following endpoints:

172.17.57.123:8081/test
172.17.57.124:8081/test

# load balanced url
172.17.57.160:80

Our simple configuration file will then look like this

global
        log 127.0.0.1   local0
        log 127.0.0.1   local1 notice
        #log loghost    local0 info
        maxconn 4096
        chroot /usr/share/haproxy
        uid 99
        gid 99
        daemon
        #debug
        #quiet

defaults
        log     global
        mode    http
        option  httplog
        option  dontlognull
        retries 3
        redispatch
        maxconn 2000
        contimeout      5000
        clitimeout      50000
        srvtimeout      50000

listen  servicefarm 172.17.57.160:80
        mode http
        cookie SERVERID insert
        balance roundrobin
        option httpclose
        option forwardfor
        stats enable
        stats auth myuser:mypassword 
        server server1 172.17.57.123:8081 cookie SERVER1 check inter 2000 rise 2 fall 5
        server server2 172.17.57.124:8081 cookie SERVER2 check inter 2000 rise 2 fall 5

“server1” and “server2” are the server names that will appear in the log files, while “SERVER1” and “SERVER2” will be the cookie strings returned by HAProxy.

Here is what actually happens with the simple HTTP load-balancing with cookie insertion specified above:

  • HAProxy will receive clients requests.
  • If a request does not contain a cookie, it will be forwarded to a valid server.
  • In return, a cookie “SERVERID” will be inserted in the response holding the server name (eg: “SERVER1”).
  • When the client comes again with the cookie “SERVERID=SERVER1”, HAProxy will know that it must be forwarded to server1. The cookie will be removed so that the server does not see it.
  • If “server1” dies, the requests will be sent to another valid server (“server2”)and a cookie will be reassigned.

Next, HAProxy can be started with:

$ ./haproxy -f haproxy.cfg

Now, any calls you make to 172.17.57.160:80/test will be load balanced to either “server1” or “server2”. Fiddler is a nice and simple tool that you can use to inspect your HTTP traffic.

HAProxy also provides a nice stats page that can be accessed at

http://172.17.57.160/haproxy?stats

With the configuration above, the username will be “myuser” and the password “mypassword”.

Lastly, if you ever need to do a hot redeploy of HAProxy, such as picking up an updated configuration file, you can run:

$ ./haproxy -f haproxy.cfg -p haproxy.pid -sf $(cat haproxy.pid)