Nginx+Keepalived 双主配置

分类:CentOS教程 阅读:85084 次

一、架构

在Keepalived + Nginx高可靠负载均衡架构中,keepalived负责实现High-availability (HA) 功能控制前端机VIP(虚拟网络地址),当有设备发生故障时,热备服务器可以瞬间将VIP自动切换过来,实际运行中体验只有2秒钟切换时间,DNS服务可以负责前端VIP的负载均衡。

二、拓扑

Nginx+Keepalived 双主配置

三、简单原理

Nginx-Keepalived-M(nginx主服务器)、Nginx-Keepalived-S(备服务器)两台服务器均通过keepalived软件把eth0网卡绑上一个虚拟IP(VIP1)地址:172.16.1.20,此VIP1当前由谁承载着服务就绑定在谁的eth0上,当Nginx-Keepalived-M发生故障时,Nginx-Keepalived-S会通过/etc/keepalived/keepalived.conf文件中设置的心跳时间advert_int 1检查,无法获取Nginx-Keepalived-M正常状态后瞬间切换到Nginx-Keepalived-S上来实现热双机负载均衡,当Nginx-Keepalived-M恢复后keepalived会通过priority 参数判断优先权将虚拟VIP1地址172.16.1.20重新绑定给Nginx-Keepalived-M的eth0网卡;同理,虚拟IP(VIP2)地址172.16.1.21把先前的Nginx-Keepalived-S当做了主服务器,Nginx-Keepalived-M当成了辅服务器,来实现热双机互备负载均衡。

四、环境

1、Centos6.3 Mini x64 (Nginx-Keepalived-M)IP:172.16.1.22 Vip:172.16.1.20

2、Centos6.3 Mini x64 (Nginx-Keepalived-S) IP:172.16.1.23 Vip:172.16.1.21

五、安装配置

分别在Nginx-Keepalived-M和Nginx-Keepalived-S安装nginx 以及keepalived,安装过程略过。

1、软件安装路径

/usr/local/nginx

/usr/local/keepalived

#cp /usr/local/keepalived/etc/keepalived /etc/keepalived

2、nginx主服务器的keepalived配置

#vi /etc/keepalived/keepalived.conf

——————————————————————-

! Configuration File for keepalived
# written byNginx+Keepalived 双主配置ucg.me
global_defs {
router_id Nginx_Id_1
}

vrrp_script chk_nginx {
script “/usr/local/keepalived/etc/check_http.sh” #定义检测脚本
interval 2 #检测间隔
weight 2
}
vrrp_instance Nginx1 { #定义一个实例
state MASTER #定义为 master
interface eth0
virtual_router_id 51 # 0-255 在同一个 instance 中一致 在整个 vrrp 中唯一
priority 150 #优先级,优先级最大的会成为 master
authentication {
auth_type PASS
auth_pass 1111
}
track_script { #检查脚本
chk_nginx
}
virtual_ipaddress { #此实例的浮动 IP
172.16.1.20
}
}
vrrp_instance Nginx2 {
state BACKUP
interface eth0
virtual_router_id 52
priority 110
authentication {
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
172.16.1.21
}
}

保存退出

—————————————————————?

检测脚本:

#vi/usr/local/keepalived/etc/check_http.sh

————————————————————

#!/bin/bash
if [ "$(ps -ef | grep "nginx: master process"| grep -v grep )" == "" ]

then
killall -9 keepalived

fi

保存退出

———————————————

3、nginx备服务器的keepalived配置

vi /etc/keepalived/keepalived.conf

——————————————————

! Configuration File for keepalived
# written byNginx+Keepalived 双主配置ucg.me
global_defs {
router_id Nginx_Id_2
}
vrrp_script chk_nginx {
script “/usr/local/keepalived/etc/check_http.sh”
interval 2
weight 2
}
vrrp_instance Nginx1 {
state BACKUP
interface eth0
virtual_router_id 51
priority 110
authentication {
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
172.16.1.20
}
}
vrrp_instance Nginx2 {
state MASTER
interface eth0
virtual_router_id 52
priority 150
authentication {
auth_type PASS
auth_pass 1111
}
track_script {
chk_nginx
}

virtual_ipaddress {
172.16.1.21
}
}

六、总结

nginx+keepalived双机互备就此结束。