综合架构--负载均衡-keepalived

一、keepalived作用

  Keepalived的作用是检测服务器的状态,如果有一台web服务器宕机,或工作出现故障,Keepalived将检测到,并将有故障的服务器从系统中剔除,同时使用其他服务器代替该服务器的工作,当服务器工作正常后Keepalived自动将服务器加入到服务器群中,这些工作全部自动完成,不需要人工干涉,需要人工做的只是修复故障的服务器。

二、keepalived的配置

  在上一章的基础上 添加一台lb02

    lb02 ip 10.0.0.6

  在两台lb01与lb02 上安装keepalived 

yum install -y keepalived

三、修改 lb01 中keepalived 的配置文件

  

[root@lb01 ~]# cat /etc/keepalived/keepalived.conf

! Configuration File for keepalived
global_defs {
   router_id LB01    #定义名字
}
vrrp_instance VI_1 {   
                         
    state MASTER         #设置该主机为主 
    interface eth0        #网卡
    virtual_router_id 51  #唯一标示id
    priority 150          #权重比权重高优先级高
    advert_int 1            #心跳检测 每隔一秒 
                              
    authentication {      
        auth_type PASS    #加密方式
        auth_pass 1111    #加密密码,一般四位标示
    }
    virtual_ipaddress {   
     10.0.0.3/24 dev eth0 label eth0:1   #虚拟ip VIP 设置后访问该ip即可达到效果,主副主机的虚拟ip需一致
    }
}

  修改lb02中的keepalived.conf 配置文件

[root@lb02 ~]# cat /etc/keepalived/keepalived.conf
! Configuration File for keepalived
global_defs {
   router_id LB02 
}

vrrp_instance VI_1 {   
             
    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  
    }
}

四、测试效果

lb01主上查看虚拟ip 10.0.0.3

[root@lb01 ~]# ip a|grep 0.3
    inet 10.0.0.3/24 scope global eth0:1

lb02备份上查看虚拟ip

[root@lb02 ~]# ip a|grep 0.3
    inet6 fe80::dfa2:ce90:78b6:8033/64 scope link tentative noprefixroute dadfailed 
[root@lb02 ~]# 

之后测试 

[root@web01 ~]# curl 10.0.0.3
www web02
[root@web01 ~]# curl 10.0.0.3
www web01
[root@web01 ~]# curl 10.0.0.3
www web02
[root@web01 ~]# 

当lb01keepalived关掉时 

[root@lb01 ~]# systemctl restart keepalived.service 
[root@lb01 ~]# ip a|grep 0.3
    inet 10.0.0.3/24 scope global eth0:1
[root@lb01 ~]# systemctl stop keepalived.service 
[root@lb01 ~]# ip a |grep 0.3
[root@lb01 ~]# 

在lb02 查看 发现02中虚拟ip 10.0.0.3已启动

[root@lb02 ~]# ip a|grep 0.3
    inet 10.0.0.3/24 scope global secondary eth0:1
    inet6 fe80::dfa2:ce90:78b6:8033/64 scope link tentative noprefixroute dadfailed 
[root@lb02 ~]# 

五、常见错误

[root@lb02 ~]# curl 10.0.0.3
curl: (7) Failed connect to 10.0.0.3:80; 拒绝连接
[root@lb02 ~]# 

检查nginx 服务是否启动

[root@web01 /]#  curl 10.0.0.3
curl: (7) Failed connect to 10.0.0.3:80; 没有到主机的路由
[root@web01 /]# 

检查主机防火墙是否开启

原文地址:https://www.cnblogs.com/qiang-qiang/p/10560606.html