Keepalived+Nginx主备切换实现高可用
Keepalived:
基于VRRP(虚拟路由器冗余协议)来实现对web服务的高可用方案
安装keepalived
0. 下载安装包,解压tar -zxvf xx,进入目录
1. ./configure --prefix=/data/program/keepalived --sysconf=/etc
2. 缺少依赖opensssl . yum install openssl-devel
3. 建立软链接 ln -s /data/program/keepalived/sbin/keepalived /sbin
4. ln -s /data/program/keepalived/sbin/keepalived /sbin
5. cp /data/program/keepalived-1.3.4/keepalived/etc/init.d/keepalived /etc/init.d/
6. 添加系统服务:chkconfig --add keepalived / chkconfig keepalived on
7. 服务开关 service keepalived start|stop..
keepalived日志文件配置
在/etc/rsyslog.conf里添加:local0.* /var/log/keepalived.log
重新启动keepalived和rsyslog服务:
service rsyslog restart
service keepalived restart
tail -f /var/log/keepalived.log 查看日志
keepalived+nginx实现双机热备
开发一个虚拟ip:192.168.130.100
配置两台nginx:ip192.168.130.130、131
修改Keepalived配置文件
vi /etc/keepalived/keepalived.conf
Master(主) Keepalived配置文件 |
Backup(备) Keepalived配置文件 |
vrrp_script check { script "/data/program/nginx/sbin/nginx_service.sh" interval 2 weight -9 } global_defs { router_id LVS_DEVEL } vrrp_instance VI_1 { state MASTER interface ens33 virtual_router_id 51 priority 60 advert_int 1 authentication { auth_type PASS auth_pass 2222 } virtual_ipaddress { 192.168.232.100 } track_script { check } } virtual_server 192.168.232.100 80 { delay_loop 5 lb_algo rr lb_kind NAT persistence_timeout 51 protocol TCP real_server 192.168.232.133 80 { weight 1 TCP_CHECK { connect_timeout 2 nb_get_retry 2 delay_before_retry 2 connect_port 80 }}} |
vrrp_script check { script "/data/program/nginx/sbin/nginx_service.sh" interval 2 weight -9 } global_defs { router_id LVS_DEVEL } vrrp_instance VI_1 { state BACKUP interface ens33 virtual_router_id 51 priority 40 advert_int 1 authentication { auth_type PASS auth_pass 2222 } virtual_ipaddress { 192.168.232.100 } track_script { check } } virtual_server 192.168.232.100 80 { delay_loop 5 lb_algo rr lb_kind NAT persistence_timeout 51 protocol TCP real_server 192.168.232.132 80 { weight 1 TCP_CHECK { connect_timeout 2 nb_get_retry 2 delay_before_retry 2 connect_port 80 }}} |
配置文件说明
1. vrrp_instance配置:state指定初始状态(主、备)。interface 为网卡名字。virtual_router_id 相同的为一个组。Priority为节点优先级,主的要大于备的。advert int 检查间隔,默认 1秒。auth type为认证方式。track_script 引用脚本。
2. virtual_server配置:delay_loop健康检查间隔。lb_algo 调度算法。 lb_kind负载均衡规则。 会话保持时间。Protocol使用的协议。
3. real_server配置:Weight 默认为1,0为失效。connect_timeout连接超时时间。nb_get_retry 重连次数。delay_before_retry 重连间隔时间。connect_port健康检查的端口的端口。
4. vrrp_script配置:interval脚本执行间隔。weight脚本优先级。script 脚本路径。
5.Nginx_service.sh判断nginx是否宕机,若宕机,结束Keepalived服务。
给脚本权限 chmod +x /data/program/nginx/sbin/nginx_service.sh
脚本内容:
#!/bin/sh
nginxPidNum=`ps-C nginx --no-header |wc -l`
keepalivedPidNum=`ps-C keepalived --no-header |wc -l`
if [$nginxPidNum -eq 0 ];then
killall keepalived
elif [$keepalivedPidNum -eq 0 ];then
service keepalived start
fi#p#分页标题#e#