Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create Floating IP and use it to configure HAProxy

I have recently tried to load balance my application using HAProxy and was able to do it successfully. Later, I have come across a concept called Floating IP, which can be used along with keepalived to make the load balancer highly available. I wasn't able to understand how to create the floating Ip though. How can I create Floating IP and use it to configure HAProxy? Thanks.

like image 837
mahu Avatar asked Feb 18 '16 12:02

mahu


1 Answers

Assumptions:

  • This works on Ubuntu 14.04
  • haproxy-primary IP: 198.51.100.10
  • haproxy-secondary IP: 198.51.100.20
  • shared IP: 198.51.100.50
  • Any DNS rules should point to the shared IP (198.51.100.50)

Steps:

  1. Add a firewall rule for keepalived # 224.0.0.18 is the keepalived multicast address
    1. sudo ufw allow in from 198.51.100.20 to 224.0.0.18 # on 198.51.100.10
    2. sudo ufw allow in from 198.51.100.10 to 224.0.0.18 # on 198.51.100.20
  2. Allow access to a shared IP address
    1. edit /etc/sysctl.conf
    2. set net.ipv4.ip_nonlocal_bind=1
    3. sudo sysctl -p # reload config change
  3. Install keepalived
    1. sudo apt-get install keepalived
  4. Configure keepalived on both servers
    1. Edit/create /etc/keepalived/keepalived.conf
    2. See example file below # the priority MUST be different on the primary and secondary servers!
  5. Restart keepalived
    1. sudo service keepalived restart
  6. Listen on the shared IP address
    1. Edit /etc/haproxy/haproxy.cfg
    2. bind 198.51.100.50:80
  7. Restart haproxy (on both haproxy servers)
    1. sudo service haproxy restart
  8. Verify proper failover
    1. primary: sudo ip addr show | grep eth0 # should list the shared IP
    2. secondary: sudo ip addr show | grep eth0 # should NOT list the shared IP
    3. primary: sudo service haproxy stop
    4. primary: sudo ip addr show | grep eth0 # should NOT list the shared IP
    5. secondary: sudo ip addr show | grep eth0 # should list the shared IP
    6. primary: sudo service haproxy start
    7. primary: sudo ip addr show | grep eth0 # should list the shared IP
    8. secondary: sudo ip addr show | grep eth0 # should NOT list the shared IP

/etc/keepalived/keepalived.conf

     vrrp_script chk_haproxy {      # Requires keepalived-1.1.13
       script "killall -0 haproxy"  # cheaper than pidof
       interval 2 # check every 2 seconds
       weight 2 # add 2 points of priority if OK
     }
     vrrp_instance VI_1 {
       interface eth0
       state MASTER
       virtual_router_id 51
       priority 101 # 101 on primary, 100 on secondary
       virtual_ipaddress {
         198.51.100.50
       }
       track_script {
         chk_haproxy
       }
     }
like image 56
Matt Rice Avatar answered Oct 02 '22 12:10

Matt Rice