Installing and Configuring HAProxy on Linux

HAProxy – proxy server for load balancing of TCP and HTTP applications, a method of distribution to multiple servers.

The Haproxy installation command in Ubuntu / Debian:

sudo apt-get install haproxy

For CentOS:

yum install haproxy

To view the installed version, you can use the command:

haproxy -v

We will check whether it will automatically start when the system is turned on, there should be ENABLED = 1 (in the nano editor CTRL+X to exit, y/n to save or cancel changes):

sudo nano /etc/default/haproxy

In CentOS, simply execute the command:

chkconfig haproxy on

Make a copy of the configuration file just in case:

sudo cp /etc/haproxy/haproxy.cfg{,.original}

Open the main configuration file in the editor:

sudo nano /etc/haproxy/haproxy.cfg

I will give an example of a configuration:

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
    retries 3
        
listen webfarm 0.0.0.0:80
    mode http
    stats enable
    stats uri /haproxy?stats
    stats auth user:password
    maxconn 5000
    balance roundrobin
    option httpclose
    option forwardfor
    server webserver01 192.168.88.50:80 check
    server webserver02 192.168.88.51:80 check

Parameter maxconn 5000 defines the maximum number of simultaneous connections, 0 is used to remove the limit, if not specified, it will be standard 2000.

For example, to use Apache2 on the same local machine, change its /etc/apache2/ports.conf and /etc/apache2/sites-enabled/ configuration files from 80 to 81 for example, and /etc/haproxy/haproxy. cfg we indicate:

server webserver01 0.0.0.0:81 check

Each time after a configuration change, you must restart:

sudo service apache2 restart
sudo service haproxy restart

This completes the installation and the basic configuration of HAProxy.