简介

在生产工作中,后台的服务器并不可能永远都处于正常运行状态,若服务器发生宕机,为了不影响正在进行的业务以及给用户更好的体验,我们可以通过keepalived监控后台服务器运行情况,当有服务器发生故障时,会从把该服务器剔除出LVS转发策略;等到服务器恢复正常后,keepalived也会重新把该服务器加入LVS转发策略中

前期准备

准备三台centos7虚拟机,配置IP地址和hostname,同步时间,关闭防火墙和selinux,配置IP地址和hostname映射 在node2和node3中部署httpd服务并修改首页内容

hostname ip index.html
node1 192.168.29.143 --
node2 192.168.29.142 client2
node3 192.168.29.144 client1

配置LVS负载均衡策略 详情可参考:https://blog.51cto.com/14832653/2501128

[root@node1 ~]# yum install keepalived -y

修改配置文件

[root@node1 ~]# vi /etc/keepalived/keepalived.conf 
! Configuration File for keepalived

global_defs {
   notification_email {
     acassen@firewall.loc
     failover@firewall.loc
     sysadmin@firewall.loc
   }
   notification_email_from Alexandre.Cassen@firewall.loc
   smtp_server 192.168.200.1
   smtp_connect_timeout 30
   router_id LVS_DEVEL
   vrrp_skip_check_adv_addr
   #1.3+版本需要把此行注释掉才能PING通
   #vrrp_strict
   vrrp_garp_interval 0
   vrrp_gna_interval 0
}

#组建vrrp实例组
vrrp_instance VI_1 {
    state BACKUP
    interface ens33
    virtual_router_id 51
    virtual_ipaddress {
	192.168.29.122
    }
    priority 100
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass 1111
    }
}
#设定真实服务器地址
virtual_server 192.168.29.122 80 {
	delay_loop 3
	lb_algo rr
	lb_kind DR
	protocol TCP
	real_server 192.168.29.142 80 {
		weight 1
		HTTP_GET {
		#url检测
		url {
		#指定所要检测的页面所在位置
		path /index.html
		status_code 200
		}
		}
		#tcp检测
		TCP_CHECK {
			connect_timeout 3
			nb_get_retry 3
			delay_before_retry 3
		}	
	}
	real_server 192.168.29.144 80 {
		weight 1
		HTTP_GET {
		url {
		path /index.html
		status_code 200
		}
		}
		TCP_CHECK {
			connect_timeout 3
			nb_get_retry 3
			delay_before_retry 3
		}	
	}
}

#启动keepalived服务
[root@node1 ~]# systemctl start keepalived.service 

测试验证

在这里插入图片描述 在这里插入图片描述 关闭node2的httpd服务

[root@node2 ~]# systemctl stop httpd.service 

在这里插入图片描述 一直刷新不会报错但是仅能访问node3结点

[root@node1 ~]# ipvsadm -L
IP Virtual Server version 1.2.1 (size=4096)
Prot LocalAddress:Port Scheduler Flags
  -> RemoteAddress:Port           Forward Weight ActiveConn InActConn
TCP  node1:http rr
  -> node3:http                   Route   1      2          0         

重启node2的httpd服务

[root@node2 ~]# systemctl start httpd.service 

在这里插入图片描述 在这里插入图片描述

[root@node1 ~]# ipvsadm -L
IP Virtual Server version 1.2.1 (size=4096)
Prot LocalAddress:Port Scheduler Flags
  -> RemoteAddress:Port           Forward Weight ActiveConn InActConn
TCP  node1:http rr
  -> node2:http                   Route   1      0          0         
  -> node3:http                   Route   1      2          0