如何创建浮动IP并使用它来配置HAProxy

时间:2016-02-18 12:54:54

标签: load-balancing haproxy floating-ip

我最近尝试使用HAProxy对我的应用程序进行负载均衡,并且能够成功完成。后来,我遇到了一个名为Floating IP的概念,它可以与keepalived一起使用,以使负载均衡器具有高可用性。虽然我无法理解如何创建浮动Ip。如何创建浮动IP并使用它来配置HAProxy? 感谢。

1 个答案:

答案 0 :(得分:9)

假设:

  • 适用于Ubuntu 14.04
  • haproxy-primary IP:198.51.100.10
  • haproxy-secondary IP:198.51.100.20
  • 共享IP:198.51.100.50
  • 任何DNS规则都应指向共享IP(198.51.100.50)

步骤:

  1. 为keepalived添加防火墙规则#224.0.0.18是keepalived多播地址
    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. 允许访问共享的IP地址
    1. 修改/etc/sysctl.conf
    2. 设置net.ipv4.ip_nonlocal_bind=1
    3. sudo sysctl -p #reload config change
  3. 安装keepalived
    1. sudo apt-get install keepalived
  4. 在两台服务器上配置keepalived
    1. 修改/创建/etc/keepalived/keepalived.conf
    2. 请参阅下面的示例文件#主服务器和辅助服务器上的优先级必须不同!
  5. 重新启动keepalived
    1. sudo service keepalived restart
  6. 收听共享的IP地址
    1. 修改/etc/haproxy/haproxy.cfg
    2. bind 198.51.100.50:80
  7. 重新启动haproxy(在两个haproxy服务器上)
    1. sudo service haproxy restart
  8. 验证是否有正确的故障转移
    1. primary:sudo ip addr show | grep eth0#应列出共享IP
    2. secondary:sudo ip addr show | grep eth0#不应列出共享IP
    3. primary:sudo service haproxy stop
    4. primary:sudo ip addr show | grep eth0#不应列出共享IP
    5. secondary:sudo ip addr show | grep eth0#应列出共享IP
    6. primary:sudo service haproxy start
    7. primary:sudo ip addr show | grep eth0#应列出共享IP
    8. secondary:sudo ip addr show | grep eth0#不应列出共享IP
  9. /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
           }
         }