Keepalived
Keepalived的作⽤是检测服务器的状态,如果有⼀台web服务器宕机,或⼯作出现故障,Keepalived将检测到,并将有故障的服务器从系统中剔除,同时使⽤其他服务器代
替该服务器的⼯作,当服务器⼯作正常后Keepalived⾃动将服务器加⼊到服务器群中,这些⼯作全部⾃动完成,不需要⼈⼯⼲涉,需要⼈⼯做的只是修复故障的服务器。
⼀个监控+⾃愈的软件
VRRP协议
http://www.keepalived.org/download.html wget http://www.keepalived.org/software/keepalived-2.0.8.tar.
#cat keepalived_install.sh #!/bin/bash pkg=keepalived-2.0.8.tar.g tar xf $pkg yum -y install kernel-devel ln -s /usr/src/kernels/3.10.0-862.14.4.el7.x86_64/ /usr/src/linux cd keepalived-2.0.8/ yum install openssl-* -y ./configure --prefix=/usr/local/keepalived make make install mkdir -pv /etc/keepalived cp /usr/local/keepalived/etc/keepalived/keepalived.conf /etc/keepalived/ ln -s /usr/local/keepalived/sbin/keepalived /sbin
yum install keepalived -y
keepalived 始终保证负载服务器有一台可以正常工作:原理
keepalived对主 网卡设置虚拟ip,同时用户访问真实ip,
对每一台
nginx监听虚拟ip,但是这个虚拟ip由keep根据niginx状态切换。
服务监听网卡上没有的ip地址:
echo 'net.ipv4.ip_nonlocal_bind = 1' >>/etc/sysctl.conf
sysctl -p
配置Nginx集群
upstream web { server 192.168.10.42 max_fails=2 fail_timeout=3; server 192.168.10.43 max_fails=2 fail_timeout=3; server { listen 192.168.10.213:80; server_name localhost; location / { proxy_pass http://web; }
配置keepalived
#cat /etc/keepalived/keepalived.conf
192.168.10.211
192.168.10.212
! Configuration File for keepalived global_defs { router_id NGINX_DEVEL } vrrp_script check_nginx { # 定义监控脚本 script "/etc/keepalived/nginx_pid.sh" interval 2 weight 2 } vrrp_instance nginx { state MASTER interface ens33 virtual_router_id 51 priority 100 advert_int 1 # 主给从 每隔一秒发送组播包 authentication { auth_type PASS auth_pass 1111 } track_script { check_nginx } virtual_ipaddress { 192.168.10.213/24 dev eth0 label eth0:1 } }
就这三处不一致,虚IP,不存在,但在一个网段
关联脚本 nginx_pid.sh
将nginx与keepalived建立联系;解决nginx挂掉,keepalived虚IP还存在
#chmod 755 /etc/keepalived/nginx_pid.sh #cat /etc/keepalived/nginx_pid.sh
#!/bin/bash web_info=$(ps -ef|grep [n]ginx|wc -l) if [ $web_info -lt 2 ] then /etc/init.d/keepalived stop fi
systemctl start keepalived
/etc/init.d/keepalived status
双主配置
vrrp_instance gorup01 { state MASTER interface eth0 virtual_router_id 51 priority 150 advert_int 1 authentication { auth_type PASS auth_pass 1111 } virtual_ipaddress { 10.0.0.3/24 dev eth0 label eth0:1 } } vrrp_instance gorup02 { state BACKUP interface eth0 virtual_router_id 52 priority 100 advert_int 1 authentication { auth_type PASS auth_pass 1111 } virtual_ipaddress { 10.0.0.4/24 dev eth0 label eth0:1 } }
vrrp_instance gorup01 { state BACKUP interface eth0 virtual_router_id 51 priority 100 advert_int 1 authentication { auth_type PASS auth_pass 1111 } virtual_ipaddress { 10.0.0.3/24 dev eth0 label eth0:1 } } vrrp_instance gorup02 { state MASTER interface eth0 virtual_router_id 52 priority 150 advert_int 1 authentication { auth_type PASS auth_pass 1111 } virtual_ipaddress { 10.0.0.4/24 dev eth0 label eth0:1 } }