centos7.1实现nginx+keepalived 负载均衡+高可用

时间:2022-12-19 10:37:53

一.环境

centos7.1操作系统      centos7.1实现nginx+keepalived 负载均衡+高可用

二.基础架构

nginx1.10.2+keepalived1.2.13               192.168.2.65

nginx1.10.2+keepalived1.2.13               192.168.2.66

web1192.168.2.83

web2192.168.2.84

虚拟IP192.168.2.67

三.安装nginx+keepalived

               centos7.1实现nginx+keepalived 负载均衡+高可用

安装网云镜像和nginx的镜像,然后使用yum install -y nginx keepalived

四.配置nginx和keepalived

nginx主 从配置一样,把原来的/etc/nginx/conf.d/default.conf 删除,重新创建一个proxy.conf,把下面配置拷贝进去就行。

vi /etc/nginx/conf.d/proxy.conf

upstream web {
    #ip_hash;
        server 192.168.2.83:80;   #默认为rr轮询,如需解决session的问题采有哈希(ip_hash)模块。
        server 192.168.2.84:80;
}
        server {
        listen 80;
        index index.php index.html index.htm;
        location / {
        proxy_pass http://web;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}


主keepalived配置,直接把原有的配置文件删除,拷贝下面的进去。

vi /etc/keepalived/keepalived.conf

! Configuration File for keepalived
global_defs {
   router_id master
}
vrrp_script chk_nginx {
    script "/etc/keepalived/nginx_check.sh"
    interval 2
    weight -20
}
vrrp_instance VI_1 {
    state MASTER
    interface em1
    virtual_router_id 51
    mcast_src_ip 192.168.2.65
    priority 100
    nopreempt
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass 1111
    }
    track_script {
        chk_nginx

 }
    virtual_ipaddress {
        192.168.2.67
    }
}

从keepalived配置,删除原有的文件内容,拷贝下面内容。

! Configuration File for keepalived




global_defs {
   router_id slave1
}
vrrp_script chk_nginx {
    script "/etc/keepalived/nginx_check.sh"
    interval 2
    weight -20
}




vrrp_instance VI_1 {
    state BACKUP
    interface em1
    virtual_router_id 51
    mcast_src_ip 192.168.2.66
    priority 90
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass 1111
    }




    track_script {
        chk_nginx
    }



    virtual_ipaddress {
        192.168.2.67
    }
}

两个web页面配置

yum install httpd -y

service httpd start

配置检测nginx服务脚本

vi /etc/keepalived/nginx_check.sh  

#!/bin/bash
A=`ps -C nginx –no-header |wc -l`
if [ $A -eq 0 ];then
    /usr/local/nginx/sbin/nginx
    sleep 2
    if [ `ps -C nginx --no-header |wc -l` -eq 0 ];then
        killall keepalived
    fi
fi

五.配置完成后,启动服务

systemctl nginx start

systemctl keepalived start

六.测试

65单独正常

centos7.1实现nginx+keepalived 负载均衡+高可用

centos7.1实现nginx+keepalived 负载均衡+高可用

66单独正常

centos7.1实现nginx+keepalived 负载均衡+高可用

centos7.1实现nginx+keepalived 负载均衡+高可用

访问67正常

centos7.1实现nginx+keepalived 负载均衡+高可用

centos7.1实现nginx+keepalived 负载均衡+高可用

虚拟IP在65上面

centos7.1实现nginx+keepalived 负载均衡+高可用

现在关闭65的nginx服务,65失效,但访问67正常,说明整体还在正常工作。虚拟IP漂移到66上面,推选66为主。

反之,关闭66主的还在服务。测试完成

centos7.1实现nginx+keepalived 负载均衡+高可用


centos7.1实现nginx+keepalived 负载均衡+高可用

centos7.1实现nginx+keepalived 负载均衡+高可用

centos7.1实现nginx+keepalived 负载均衡+高可用