Linux下Nginx + Keepalived搭建负载均衡与高可用服务

本文示例环境为两台服务器,一个虚IP

主服务器:192.168.1.110

从服务器:192.168.1.111

虚IP:192.1683.1.112

一.Nginx配置负载均衡

① 主服务器与从服务器均配置以下nginx内容:

user nginx;worker_processes  auto;

error_log  /var/log/nginx/error.log warn;

pid        /var/run/nginx.pid;

events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;
    proxy_buffer_size 512k;
    proxy_buffers 32 512k;
    proxy_busy_buffers_size 512k;
    log_format  main  ‘$remote_addr - $remote_user [$time_local] "$request" ‘
                      ‘$status $body_bytes_sent "$http_referer" ‘
                      ‘"$http_user_agent" "$http_x_forwarded_for"‘;

    access_log  /var/log/nginx/access.log  main;
    sendfile        on;
    keepalive_timeout  65;
    
    #配置上游
    upstream loadBanlance{
        ip_hash;     #把需要配置负载的服务器及服务监听端口加入进来
        server 192.168.1.110:8080;
        server 192.168.1.111:8080;
    }
   #配置监听
    server {
        listen       9000;
        server_name  localhost;

        location / {
            root   /opt/project/dist; #前端页面路径,根据实际情况填写
            index  index.html; #前端首页面
            client_max_body_size    500m;
            proxy_pass http://loadBanlance; #代理转发
        }

        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
}

②重新加载nginx

service nginx reload

二.Keepalived配置高可用

① 主服务器与从服务器配置keepalived:

*标红部分请根据自身实际环境配置

global_defs {
    notification_email {
        [email protected]            #通知邮箱
    }
    notification_email_from snsgmail.com
    smtp_server smtp.hysec.com
    smtp_connection_timeout 30
    router_id  nginx_master              # 自定义唯一id,主服务器为nginx_master,从服务器为nginx_slave
}
vrrp_script chk_http_port {
    script "/etc/keepalived/check_nginx.sh"  #检测脚本位置
    interval 2                               #(检测脚本执行的间隔)
    weight 2
}vrrp_instance VI_1 {
    state MASTER                        # 指定keepalived的角色,MASTER为主,BACKUP为从
    interface ens32                     # 当前进行vrrp通讯的网络接口卡(以实际环境为准)
    virtual_router_id 66                # 虚拟路由编号,主从要一致
    priority 100                        # 优先级,数值越大,获取处理请求的优先级越高
    advert_int 1                        # 检查间隔,默认为1s(vrrp组播周期秒数)
    authentication {
        auth_type PASS
        auth_pass 1111
    }
    track_script {
        chk_http_port                   #(调用检测脚本)
    }virtual_ipaddress {
        192.168.1.112                   # 定义虚拟ip(VIP),可多设,每行一个
    }
}

② 附上检测脚本:

#!/bin/bash
A=`ps -C nginx --no-header | wc -l`
if [ $A -eq 0 ];then
    systemctl stop keepalived #关闭keepalived

fi

③启动keepalived,看到主服务器网卡上被添加了虚Ip即为配置生效

systemctl keepalived start

相关推荐