linux下nginx结合keepalived实现主从切换的配置
解决方法:
实现一个主nginx宕机,请求转到另一个nginx中。
1.确保两台nginx已启动,假如端口分别是192.168.0.2:8080和192.168.0.3:8080
2.分别在两台nginx所在的主机192.168.0.2和192.168.0.3中安装keepalived,安装keepalived请参考:http://www.yayihouse.com/yayishuwu/chapter/1649
3.分别再两个主机的/etc/keepalived/下新建一个check_nginx_pid.sh文件,内容如下:
#!/bin/bash
A=`ps -C nginx --no-header |wc -l`
if [ $A -eq 0 ];then
/usr/local/nginx/nginx/sbin/nginx #如果检测到nginx挂掉了就重启nginx
if [ `ps -C nginx --no-header |wc -l` -eq 0 ];then #nginx重启失败,则停掉keepalived服务,进行VIP转移
killall keepalived
fi
fi
4.分别修改两个keepalived的配置文件/etc/keepalived/keepalived.conf
假如把192.168.0.2:8080的nginx的keepalived设置为主,把192.168.0.3:8080的nginx的keepalived设置为备用
主keepalived.conf:
global_defs {
notification_email {
997914490@qq.com
}
notification_email_from sns-lvs@gmail.com
smtp_server smtp.hysec.com
smtp_connection_timeout 30
router_id nginx_master # 设置nginx master的id,在一个网络应该是唯一的
}
vrrp_script chk_http_port {
script "/etc/keepalived/check_nginx_pid.sh" #最后手动执行下此脚本,以确保此脚本能够正常执行
interval 2 #(检测脚本执行的间隔,单位是秒)
weight 2
}
vrrp_instance VI_1 {
state MASTER # 指定keepalived的角色,MASTER为主,BACKUP为备
interface eth0 # 当前进行vrrp通讯的网络接口卡(当前centos的网卡)
virtual_router_id 66 # 虚拟路由编号,主从要一直
priority 100 # 优先级,数值越大,获取处理请求的优先级越高
advert_int 1 # 检查间隔,默认为1s(vrrp组播周期秒数)
authentication {
auth_type PASS
auth_pass 1111
}
track_script {
chk_http_port #(调用检测脚本)
}
virtual_ipaddress {
192.168.0.200 # 定义虚拟ip(VIP),可多设,每行一个
}
}
从keepalived.conf:
global_defs {
notification_email {
997914490@qq.com
}
notification_email_from sns-lvs@gmail.com
smtp_server smtp.hysec.com
smtp_connection_timeout 30
router_id nginx_backup # 设置nginx backup的id,在一个网络应该是唯一的
}
vrrp_script chk_http_port {
script "/etc/keepalived/check_nginx_pid.sh"
interval 2 #(检测脚本执行的间隔)
weight 2
fall 3
}
vrrp_instance VI_1 {
state BACKUP # 指定keepalived的角色,MASTER为主,BACKUP为备
interface eth0 # 当前进行vrrp通讯的网络接口卡(当前centos的网卡)
virtual_router_id 66 # 虚拟路由编号,主从要一直
priority 99 # 优先级,数值越大,获取处理请求的优先级越高
advert_int 1 # 检查间隔,默认为1s(vrrp组播周期秒数)
authentication {
auth_type PASS
auth_pass 1111
}
track_script {
chk_http_port #(调用检测脚本)
}
virtual_ipaddress {
192.168.0.200 # 定义虚拟ip(VIP),可多设,每行一个
}
}
5.启动两个keepalived,执行service keepalived start启动
6.使用192.168.0.200:8080访问即可,如果正常访问,说明配置正常;
如果此时杀掉主nginx,而且主nginx又重启了(check_nginx_pid.sh配置了重启),说明执行了check_nginx_pid.sh文件,这是正常的;
如果主nginx重启失败,而且192.168.0.200:8080访问失败,说明没转发到备用nginx,检查一下check_nginx_pid.sh是否被正常执行了,不被执行的原因一般来说是权限不够,到/etc/keepalived/目录执行 chmod u+x *即可。
本文链接:http://www.yayihouse.com/yayishuwu/chapter/1660