插件窝 干货文章 Nginx+Keepalived怎么实现双机热备

Nginx+Keepalived怎么实现双机热备

服务器 Keepalived Nginx 双机 601    来源:    2025-04-21

Nginx+Keepalived双机热备实现方案

一、方案概述

Nginx+Keepalived双机热备方案通过Keepalived实现VIP(虚拟IP)的自动漂移,当主服务器故障时,备用服务器会自动接管VIP,确保服务不间断。

二、环境准备

  1. 两台服务器(主备各一台)

    • 主服务器: 192.168.1.100
    • 备服务器: 192.168.1.101
    • 虚拟VIP: 192.168.1.200
  2. 确保两台服务器:

    • 已安装Nginx并能正常提供服务
    • 网络互通
    • 防火墙允许VRRP协议(通常使用IP协议号112)

三、安装配置Keepalived

1. 安装Keepalived

在两台服务器上执行:

# CentOS/RHEL
yum install keepalived -y

# Ubuntu/Debian
apt-get install keepalived -y

2. 主服务器配置

编辑/etc/keepalived/keepalived.conf:

global_defs {
   router_id nginx_master  # 唯一标识,建议使用主机名
}

vrrp_script chk_nginx {
    script "/usr/bin/killall -0 nginx"  # 检测nginx进程是否存在
    interval 2  # 每2秒检测一次
    weight -20   # 检测失败时优先级降低20
}

vrrp_instance VI_1 {
    state MASTER    # 主服务器
    interface eth0  # 网卡名称,根据实际情况修改
    virtual_router_id 51  # 虚拟路由ID,主备必须相同
    priority 100    # 优先级,主服务器高于备服务器
    advert_int 1    # 主备同步检查间隔

    authentication {
        auth_type PASS
        auth_pass 1111  # 密码,主备必须相同
    }

    virtual_ipaddress {
        192.168.1.200  # 虚拟VIP
    }

    track_script {
        chk_nginx  # 关联nginx检测脚本
    }
}

3. 备服务器配置

编辑/etc/keepalived/keepalived.conf:

global_defs {
   router_id nginx_backup
}

vrrp_script chk_nginx {
    script "/usr/bin/killall -0 nginx"
    interval 2
    weight -20
}

vrrp_instance VI_1 {
    state BACKUP     # 备服务器
    interface eth0
    virtual_router_id 51
    priority 90     # 优先级低于主服务器
    advert_int 1

    authentication {
        auth_type PASS
        auth_pass 1111
    }

    virtual_ipaddress {
        192.168.1.200
    }

    track_script {
        chk_nginx
    }
}

四、启动服务

在两台服务器上执行:

systemctl start keepalived
systemctl enable keepalived

五、验证配置

  1. 在主服务器上查看VIP绑定:
ip addr show eth0

应该能看到VIP绑定在主服务器的eth0网卡上

  1. 停止主服务器的Nginx服务:
systemctl stop nginx
  1. 观察VIP是否自动漂移到备服务器

  2. 恢复主服务器Nginx后,VIP应该会自动切回主服务器(因为主服务器优先级更高)

六、高级配置选项

  1. 邮件通知: 在global_defs中添加:
notification_email {
    admin@example.com
}
notification_email_from keepalived@example.com
smtp_server smtp.example.com
smtp_connect_timeout 30
  1. 多VIP支持: 在virtual_ipaddress块中添加多个VIP

  2. Nginx健康检查增强: 使用更复杂的检查脚本,例如:

#!/bin/bash
if [ "$(curl -s -o /dev/null -w '%{http_code}' http://localhost/health)" = "200" ]; then
    exit 0
else
    exit 1
fi

七、常见问题解决

  1. VIP不漂移:

    • 检查防火墙是否阻止了VRRP协议
    • 确保virtual_router_id在主备服务器上一致
    • 检查priority设置是否正确
  2. 脑裂问题:

    • 确保网络连接稳定
    • 考虑使用多播或单播通信(在vrrp_instance中添加unicast_peer配置)
  3. 日志查看:

journalctl -u keepalived -f

通过以上配置,您就实现了Nginx的高可用双机热备方案,确保在单台服务器故障时服务能够自动切换,保障业务连续性。