Install and Configure HAProxy on Ubuntu

HAProxy is an efficient and lightweight proxy for Debian Linux distributions. This guide will run through installation, configuration for round robin load balancing including health checks and URL based proxy pass.

First up, update repositories

sudo apt-get update

Then install HAProxy

sudo apt-get install haproxy

Once installed, HAProxy need to be enabled. Edit the following file and set ENABLED to 1

sudo nano /etc/default/haproxy

Create a backup of the default config file

sudo cp /etc/haproxy/haproxy.cfg /etc/haproxy/haproxy_back.cfg

Then edit the default config file

sudo nano /etc/haproxy/haproxy.cfg

Clear any existing configuration and add the following –

Set maximum connections and set a user for HAProxy to run as

maxconn 2000
user haproxy
group haproxy

Some generic defaults for timeout, retry attempts and mode

mode http
retries 3
option redispatch
timeout connect 5000
timeout client 10000
timeout server 10000

Define some frontend parameters. This will allow us to pass to different backends based on URL

frontend http-in
acl host_1 hdr(host) -i
acl host_nginx hdr(host) -i
acl host_nginx hdr(host) -i

Match frontends to backends

use_backend firstsite_redirect if host_1
use_backend nginx if host_nginx

Define backend locations and settings.

This will pass any requests for to server on port 8080. Requests to and will be passed to servers and on port 8080 on a round robin basis. This means requests will alternate between servers. cookie s1 and cookie s2 will set cookies, maintaining session stickiness with a single server, otherwise users could be passed between servers as they browse a site. Finally, check performs health checks and will pass all requests to the other backend, should one fail.

backend firstsite_redirect
mode http
option forwardfor
server firstserver

backend nginx
mode http
balance roundrobin
option httpclose
option forwardfor
cookie SRVNAME insert
server nginx01 cookie s1 check
server nginx02 cookie s2 check

That’s it! Instruct your web server(s) to listen on port 8080 and you’re ready to party. I’d suggest creating a site on each backend. On one output “I’m server 1” on the other “I’m server 2.” Watch what happens when you refresh the page (you should stick with the same server.) What happens when you browse in incognito mode? (Server should alternate as cookies won’t be stored.) If you shut down or stop the web service on one backend, the other should take over all requests.

Happy load balancing!

Leave a Reply

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