Keepalived高可用(Nginx七层负载均衡)

Keepalived+Nginx

准备四台干净的机器
分别关闭防火墙和SELinux


192.168.202.130 keepalived-master
192.168.202.131 keepalived-backup
192.168.202.132 nginx-server1
192.168.202.133 nginx-server2


#四台机器分别装上epel源和nginx
yum -y install epel-release
yum -y install nginx
#在keepalived的master机器上和backup机器上安装keepalived
yum -y install keepalived

配置keepalived两台机器的nginx负载
/etc/nginx/nginx.conf文件
Keepalived高可用(Nginx七层负载均衡)_第1张图片

#keepalived两台机器上的nginx负载均衡配置
[xiaobai@keepalived-master] cd /etc/nginx/conf.d/
[xiaobai@keepalived-master] vim proxy.conf
upstream xiaobai {
        server 192.168.202.132:80 weight=1 max_fails=2 fail_timeout=2;
        server 192.168.202.133:80 weight=1 max_fails=2 fail_timeout=2;
}       
server {
        listen 80;
        server_name     localhost;
        access_log  /var/log/nginx/host.access.log  main;
        
        location / {
         proxy_pass http://xiaobai;
         proxy_redirect default;
         proxy_set_header Host $http_host;
         proxy_set_header X-Real-IP $remote_addr;
         proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }
}
#保存并退出
[xiaobai@keepalived-master] systemctl start nginx
[xiaobai@keepalived-master] systemctl enable nginx
#keepalived-backup机器也要有同样的配置
#两台keepalived机器都要配置,有些地方需要改
[xiaobai@keepalived-master] cd /etc/keepalived
[xiaobai@keepalived-master] mv keepalived.conf keepalived.conf.bak
[xiaobai@keepalived-master] vim keepalived.conf
! Configuration File for keepalived   #没有实际意义

global_defs {
   router_id directory1   #backup机器上应该改为directory2
}

vrrp_instance VI_1 {
    state MASTER        #master为主,backup为备,backup机器上要改
    interface ens33     #VIP的绑定接口
    #master机器上不需要,backup机器上需要加上nopreempt,不抢占VIP
    virtual_router_id 80    #整个集群的id,backup机器也应该保持一致
    priority 100         #优先级,backup机器改为50
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass 1111
    }
    virtual_ipaddress {
        192.168.202.26/24
    }
}
#保存并退出,去backup机器上配置keepalived的配置文件
[xiaobai@keepalived-master] systemctl start keepalived
[xiaobai@keepalived-master] systemctl enable keepalived
#两台机器启动服务并开机自启
[xiaobai@keepalived-master] ip a add dev ens33 192.168.202.26/24

打开浏览器访问VIP地址192.168.202.26

Keepalived高可用(Nginx七层负载均衡)_第2张图片
刷新后
Keepalived高可用(Nginx七层负载均衡)_第3张图片
nginx的负载均衡没有问题,现在将master机器的keepalived关闭,测试高可用
Keepalived高可用(Nginx七层负载均衡)_第4张图片
关闭前VIP192.168.202.26还存在,关闭keepalived服务后再次查看ip,并没有192.168.202.26,切换到backup查看ip
Keepalived高可用(Nginx七层负载均衡)_第5张图片
刷新网页也是可以不受影响的

文中内容适用于初学者 @小白

你可能感兴趣的:(高可用)