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
global
maxconn 2000
user haproxy
group haproxy
Some generic defaults for timeout, retry attempts and mode
defaults
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
bind 0.0.0.0:80
acl host_1 hdr(host) -i firstsite.com
acl host_nginx hdr(host) -i secondsite.com
acl host_nginx hdr(host) -i thirdsite.com
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 firstsite.com to server 192.168.0.2 on port 8080. Requests to secondsite.com and thirdsite.com will be passed to servers 192.168.0.3 and 192.168.0.4 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 192.168.0.2:8080
backend nginx
mode http
balance roundrobin
option httpclose
option forwardfor
cookie SRVNAME insert
server nginx01 192.168.0.3:8080 cookie s1 check
server nginx02 192.168.0.4:8080 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!