Setup High Availability for HAProxy

To prevent service failure during disasters like server crash or so on, we have to find Single Point of Failure components and setup High Availability solutions for them.

In this article I am going to define how to setup High Availability for HAProxy service. The structure of service would be something like below:

HAProxy structure map

In this scenario, there is a Virtual IP which is 192.168.1.205, and can be used for both HAProxy servers. This VIP points to the master server (192.168.1.201) in normal conditions, and if something bad happens to this server, the VIP will point to the other server (192.168.1.200).

First of all you have to install HAProxy on both servers using this link.

After that all you need is installing and configurating keepalived service on your OS (here we use CentOS 7):

yum install keepalived -y

Then you should change the service’s configurations:

vi /etc/keepalived/keepalived.conf

And delete all it’s content and replace them with the following. For config file of Master server:

vrrp_script chk_haproxy {
    script "/usr/sbin/pidof haproxy"
    interval 1
}

vrrp_instance VI_1 {
    interface ens160
    state MASTER
    priority 200

    virtual_router_id 33
    unicast_src_ip 192.168.1.201
    unicast_peer {
        192.168.1.200
    }

    authentication {
        auth_type PASS
        auth_pass 1234567890
    }

        virtual_ipaddress {
        192.168.1.205
    }

    track_script {
        chk_haproxy
    }

    notify_master /etc/keepalived/master.sh
}

And for config file of Backup server:

vrrp_script chk_haproxy {
    script "/usr/sbin/pidof haproxy"
    interval 1
}

vrrp_instance VI_1 {
    interface ens160
    state BACKUP
    priority 100

    virtual_router_id 33
    unicast_src_ip 192.168.1.200
    unicast_peer {
        192.168.1.201
    }

    authentication {
        auth_type PASS
        auth_pass 1234567890
    }

        virtual_ipaddress {
        192.168.1.205
    }

    track_script {
        chk_haproxy
    }

    notify_master /etc/keepalived/master.sh
}

And finally you have to restart the service and enable it for next startups:

systemctl enable keepalived
systemctl restart keepalived