Keepalived ip漂移

当 Nginx 部署在多个服务器节点上,且希望在一个节点故障时,客户端流量自动切换到另一个节点时,需要使用 IP 漂移。
这里使用使用 Keepalived 实现 IP 漂移

一.安装配置 Keepalived

  1. 安装 Keepalived
    在所有运行 Nginx 的节点上安装 Keepalived:
# 在 CentOS 上
sudo yum install keepalived -y

# 在 Ubuntu 上
sudo apt update
sudo apt install keepalived -y
  1. 配置 Keepalived
    编辑 Keepalived 的配置文件(通常位于 /etc/keepalived/keepalived.conf)。

主节点配置:
假设漂移 IP 为 192.168.188.170:

vrrp_instance VI_1 {
    state MASTER
    interface eno1
    virtual_router_id 51
    priority 100
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass 123456
    }
    virtual_ipaddress {
        192.168.188.170/24 dev eno1
    }
    garp_master_refresh 30
    garp_master_refresh_repeat 3
}

备节点配置:
备节点的配置文件几乎相同,但 state 和 priority 要修改:

vrrp_instance VI_1 {
    state BACKUP
    interface eth0
    virtual_router_id 51
    priority 90
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass 123456
    }
    virtual_ipaddress {
        192.168.188.170/24 dev eno1
    }
    garp_master_refresh 30
    garp_master_refresh_repeat 3
}
  • interface: 指定网卡名称(使用 ip a 查看网卡)。
  • priority: 主节点的优先级应高于备节点。
  • auth_pass: 主备节点必须一致。
  • garp_master_refresh: 设置定期发送 Gratuitous ARP 的间隔(单位:秒)。
  • garp_master_refresh_repeat: 设置每次发送的重复次数。
  1. 启动 Keepalived
    启动并启用 Keepalived 服务:
sudo systemctl start keepalived
sudo systemctl enable keepalived

验证虚拟 IP 是否绑定到主节点:

ip a | grep 192.168.188.170

在主节点故障或停止 Keepalived 后,虚拟 IP 会漂移到备节点。

二. 与 Nginx 集成

1.在 Nginx 配置中绑定虚拟 IP:
修改
/etc/nginx/nginx.conf:

server {
    listen 80;
    server_name 192.168.188.170;
    location / {
        root /var/www/html;
        index index.html;
    }
}

2.检查 Nginx 配置并重新加载:

sudo nginx -t
sudo systemctl reload nginx

三.验证漂移效果

1.正常状态

  • 主节点提供服务,访问 http://192.168.188.170
  • 使用 ip a 验证虚拟 IP 绑定在主节点。
    2.模拟主节点故障
  • 停止主节点的 Keepalived:
sudo systemctl stop keepalived

3.恢复主节点

  • 启动主节点的 Keepalived:
sudo systemctl start keepalived
  • 虚拟 IP 应重新漂移回主节点。

四.注意事项

1.网卡配置
确保网卡允许绑定虚拟 IP ,并显式设置网卡的 ARP 配置,确保其工作状态正常。
(/etc/sysctl.conf 添加以下内容并重启):
net.ipv4.ip_nonlocal_bind = 1

net.ipv4.conf.all.arp_ignore = 1
net.ipv4.conf.all.arp_announce = 2
net.ipv4.conf.eno1.arp_ignore = 1
net.ipv4.conf.eno1.arp_announce = 2

应用配置:

sudo sysctl -p

2.防火墙设置
确保 VRRP 协议(默认 UDP 端口 112)不被防火墙阻止。

posted @ 2025-01-20 17:00  怀里的懒猫  阅读(216)  评论(0)    收藏  举报