【运维知识进阶篇】集群架构-Nginx七层负载均衡详解

为什么要使用负载均衡

当我们的Web服务器直接面向用户,往往要承载大量并发请求,单台服务器难以负荷,我使用多台Web服务器组成集群,前端使用Nginx负载均衡,将请求分散的打到我们的后端服务器集群中,实现负载的分发。那么会大大提升系统的吞吐率、请求性能。

负载均衡简单介绍

我们将负载均衡称为SLB(Server Load Balance),Nginx就是SLB的一种,负载均衡的叫法有很多,还可以叫负载、Load Balance、LB,公有云中叫SLB(阿里云负载均衡)、QLB(青云负载均衡)、CLB(腾讯云负载均衡)、ULB(ucloud负载均衡),常见的负载均衡软件有Nginx、Haproxy、LVS,Nginx是七层负载,可以造伪四层,Haproxy是七层负载、LVS是四层负载。

负载均衡分七层和四层,七层从下到上分别是1.物理层、2.数据链路层、3.网络层、4.传输层、5.会话层、6.表示层、7.应用层,而四层负载均衡仅到传输层,所以说四层负载均衡速度更快,但是七层负载均衡更贴近于服务,http协议就是七层协议,我们可以用Nginx做会话保持、URL路径规则匹配、Head头改写等等,这些四层无法实现。本篇文章我们介绍Nginx的七层负载均衡。

Nginx负载均衡配置语法

Nginx实现负载均衡都需要用proxy_pass代理模块配置

Nginx负载均衡与Nginx代理不同,Nginx的一个location仅能代理一台服务器,而Nginx负载均衡则是将客户端请求代理转发至一组upstream虚拟服务池。

一、准备主机

我们准备1台LB01作为负载均衡服务器(10.0.0.5;172.16.1.5)、2台Web服务器分别是Web01(10.0.0.7;172.16.1.7)、Web02(10.0.0.8;172.16.1.8)

二、配置Nginx

在Web01和Web02分别配置Nginx,并创建测试代码文件

[root@Web01 ~]# cat /etc/nginx/conf.d/test.conf
server {
	listen 80;
	server_name test.koten.com;
	location /{
		root /code/test;
		index index.html;
	}
}
[root@Web01 ~]# mkdir -p /code/test
[root@Web01 ~]# echo 'Web01' > /code/test/index.html
[root@Web01 ~]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
[root@Web01 ~]# systemctl restart nginx

[root@Web02 ~]# cat /etc/nginx/conf.d/test.conf
server {
	listen 80;
	server_name test.koten.com;
	location /{
		root /code/test;
		index index.html;
	}
}
[root@Web02 ~]# mkdir -p /code/test
[root@Web02 ~]# echo 'Web02' > /code/test/index.html
[root@Web02 ~]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
[root@Web02 ~]# systemctl restart nginx

三、配置Nginx负载均衡

[root@LB01 ~]# vim /etc/nginx/conf.d/test_proxy.conf  #负载均衡配置文件
upstream node {
    server 172.16.1.7;
    server 172.16.1.8;
}
server {
    listen 80;
    server_name test.koten.com;

    location / {
        proxy_pass http://node;
        include proxy_params;
        }
}
~                                                                
~                                                                
~                                                                
[root@LB01 ~]# vim /etc/nginx/proxy_params  #负载均衡调用的模块信息
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;

proxy_connect_timeout 30;
proxy_send_timeout 60;
proxy_read_timeout 60;

proxy_buffering on;
proxy_buffer_size 32k;
proxy_buffers 4 128k;
~                                                                
~                                                                
~                                                                
~                                                                
~                                                                
[root@LB01 ~]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
[root@LB01 ~]# systemctl restart nginx

四、成果展示

修改本地HOST文件并打开浏览器访问test.koten.com

e083ff73e4e043249f94ccd9e28ef558.png

刷新一下页面,显示Web02,意味着我们已经通过负载均衡访问到了Web02服务器。

3cc2b4855e7a4775a592639c1b20b5ab.png

Nginx负载均衡常见故障

Nginx负载均衡比较智能,如果一个服务器宕了,会自动访问下一个服务器,但是如果后台服务器没有宕而是返回错误,就需要我们增加一个负载均衡设置了,以保证如果出错能直接访问下一台,而不是返回错误。

 proxy_next_upstream error timeout http_500 http_502 http_503 http_504;
[root@LB01 ~]# vim /etc/nginx/conf.d/test_proxy.conf
upstream node {
    server 172.16.1.7;
    server 172.16.1.8;
}
server {
    listen 80;
    server_name test.koten.com;

    location / {
        proxy_pass http://node;
        include proxy_params;
        proxy_next_upstream error timeout http_500 http_502 http_
503 http_504; #这样如果报这些错误也会自动访问下一个服务器节点
        }
}
~                                                                
<inx/conf.d/test_proxy.conf" 14L, 274C written 

Nginx负载均衡调度算法

这样的负载均衡,每刷新一下就是一次请求,一次请求就变一次访问的服务器,我们把这种负载均衡算法,称为轮询。常见的负载均衡算法有以下几种:

调度算法概述
轮询按时间顺序逐一分配到不同的后端服务器(默认)
weight加权轮询,weight值越大,分配到的访问几率越高
ip_hash每个请求按照访问的IP的hash结果分配,这样来自同一IP的固定访问一个后端服务器
url_hash按照访问的URL的hash结果来分配请求,不同的URL定向到不同的后端服务器

least_conn

最少连接数,哪个机器连接数少就分发哪个

一、轮询配置

upstream load_pass {
    server 10.0.0.7:80;
    server 10.0.0.8:80;
}

二、权重轮询配置

upstream load_pass {
    server 10.0.0.7:80 weight=5;
    server 10.0.0.8:80;
}

三、ip_hash配置

upstream load_pass {
    ip_hash;
    server 10.0.0.7:80 weight=5;
    server 10.0.0.8:80;
}

注意:不能和weight一起使用,因为一个IP下不止一台客户端,如果客户端都走相同代理,会导致某一台服务器连接数过多。

Nginx负载均衡后端状态

一、后端Web服务器在前端Nginx负载均衡调度中的状态

状态概述
down当前的服务器不参与负载均衡,一般用于停机维护
backup预留的备份服务器
max_fails允许请求失败的次数
fail_timeout经过max_fails失败后,服务器暂停时间
max_coms限制最大的接收连接数

二、down测试

[root@LB01 ~]# vim /etc/nginx/conf.d/test_proxy.conf
upstream webs {
    server 172.16.1.7 down;
    server 172.16.1.8;
}
server {
    listen 80;
    server_name test.koten.com;

    location / {
        proxy_pass http://webs;
        include proxy_params;
        proxy_next_upstream error timeout http_500 http_502 http_
503 http_504;
        }
}
~                                                                
<inx/conf.d/test_proxy.conf" 14L, 279C written 
[root@LB01 ~]# systemctl restart nginx

浏览器访问test.koten.com刷新只显示Web02了 

9bf2fcabade744648d7748b2d958e1f6.png

三、backup测试

把Web01设为backup,刷新浏览器,发现只能访问到Web01,Web02作为预留。

[root@LB01 ~]# vim /etc/nginx/conf.d/test_proxy.conf
upstream webs {
    server 172.16.1.7 backup;
    server 172.16.1.8;
}
server {
    listen 80;
    server_name test.koten.com;

    location / {
        proxy_pass http://webs;
        include proxy_params;
        proxy_next_upstream error timeout http_500 http_502 http_
503 http_504;
        }
}
~                                                                
<inx/conf.d/test_proxy.conf" 14L, 281C written 
[root@LB01 ~]# systemctl restart nginx

2cba94926e7c478bb6aae5920072b0b6.png

把Web02down掉,发现刷新会访问Web01,预留的服务器启用。

[root@LB01 ~]# vim /etc/nginx/conf.d/test_proxy.conf
upstream webs {
    server 172.16.1.7 backup;
    server 172.16.1.8 down;
}
server {
    listen 80;
    server_name test.koten.com;

    location / {
        proxy_pass http://webs;
        include proxy_params;
        proxy_next_upstream error timeout http_500 http_502 http_
503 http_504;
        }
}
~                                                                
<inx/conf.d/test_proxy.conf" 14L, 286C written 
[root@LB01 ~]# systemctl restart nginx

四、max_fails失败次数和fail_timeout时间内失败多少次则标记down

[root@LB01 ~]# vim /etc/nginx/conf.d/test_proxy.conf
upstream webs {
    server 172.16.1.7 max_fails=2 fail_timeout=10s;
    server 172.16.1.8;
}
server {
    listen 80;
    server_name test.koten.com;

    location / {
        proxy_pass http://webs;
        include proxy_params;
        proxy_next_upstream error timeout http_500 http_502 http_
503 http_504;
        }
}
~                                                                
<inx/conf.d/test_proxy.conf" 14L, 303C written 
[root@LB01 ~]# systemctl restart nginx

五、max_conns最大TCP连接数

[root@LB01 ~]# vim /etc/nginx/conf.d/test_proxy.conf
upstream webs {
    server 172.16.1.7 max_conns=1;
    server 172.16.1.8;
}
server {
    listen 80;
    server_name test.koten.com;

    location / {
        proxy_pass http://webs;
        include proxy_params;
        proxy_next_upstream error timeout http_500 http_502 http_
503 http_504;
        }
}
~                                                                
<inx/conf.d/test_proxy.conf" 14L, 286C written 
[root@LB01 ~]# systemctl restart nginx

Nginx负载均衡健康检查

 我们采用第三方模块nginx_upstream_check_module来检测后端服务的健康状态,我们新克隆一个LB02用来测试,配置yum源,安装上Nginx。

一、安装依赖包

[root@LB02 ~]# yum install -y gcc glibc gcc-c++ pcre-devel openssl-devel patch

二、下载nginx源码包和nginx_upstream_check模块第三方模块

[root@LB02 ~]# wget http://nginx.org/download/nginx-1.22.1.tar.gz
[root@LB02 ~]# wget https://github.com/yaoweibin/nginx_upstream_check_module/archive/master.zip

三、解压nginx源码包以及第三方模块

[root@LB02 ~]# tar xf nginx-1.22.1.tar.gz
[root@LB02 ~]# unzip master.zip

四、进入nginx目录,打补丁(nginx的版本是1.22补丁就选择1.22的,或者是相近的版本号,p1代表在nginx目录,p0是不在nginx目录),打好补丁后编译并安装

[root@LB02 ~]# cd nginx-1.22.1/
[root@LB02 nginx-1.22.1]# patch -p1 <../nginx_upstream_check_module-master/check_1.20.1+.patch
[root@LB02 nginx-1.22.1]# ./configure --prefix=/etc/nginx --sbin-path=/usr/sbin/nginx --modules-path=/usr/lib64/nginx/modules --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --pid-path=/var/run/nginx.pid --lock-path=/var/run/nginx.lock --http-client-body-temp-path=/var/cache/nginx/client_temp --http-proxy-temp-path=/var/cache/nginx/proxy_temp --http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp --http-uwsgi-temp-path=/var/cache/nginx/uwsgi_temp --http-scgi-temp-path=/var/cache/nginx/scgi_temp --user=nginx --group=nginx --with-compat --with-file-aio --with-threads --with-http_addition_module --with-http_auth_request_module --with-http_dav_module --with-http_flv_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_mp4_module --with-http_random_index_module --with-http_realip_module --with-http_secure_link_module --with-http_slice_module --with-http_ssl_module --with-http_stub_status_module --with-http_sub_module --with-http_v2_module --with-mail --with-mail_ssl_module --with-stream --with-stream_realip_module --with-stream_ssl_module --with-stream_ssl_preread_module --add-module=/root/nginx_upstream_check_module-master --with-cc-opt='-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -fPIC' --with-ld-opt='-Wl,-z,relro -Wl,-z,now -pie'
[root@LB02 nginx-1.22.1]# make && make install

五、在配置文件上增加健康检查的功能

[root@LB02 conf.d]# cat proxy_web.conf
upstream web {
    server 172.16.1.7:80 max_fails=2 fail_timeout=10s;
    server 172.16.1.8:80 max_fails=2 fail_timeout=10s;
    check interval=3000 rise=2 fall=3 timeout=1000 type=tcp;
    #interval  检测间隔时间,单位为毫秒
    #rise      表示请求2次正常,标记此后端的状态为up
    #fall      表示请求3次失败,标记此后端的状态为down
    #type      类型为tcp
    #timeout   超时时间,单位为毫秒
}

server {
    listen 80;
    server_name web.koten.com;
    location / {
        proxy_pass http://web;
        include proxy_params;
    }

    location /upstream_check {
        check_status;
    }
}

六、本地hosts后浏览器访问可以查看健康状态 

54e39bceff7b4b93bbe87a41cc147ed9.png

Nginx负载均衡会话保持

一、两种处理会话保持问题的方法

1、使用nginx的ip_hash,根据客户端不同的IP,将请求分配到对应的IP

2、基于服务端的session会话共享(NFS、MySQL、memcache、redis、file)

二、session和cookie的区别

cookie是保存到客户端浏览器的信息,session是保存到服务端的信息,用户登录账号密码,会将cookie保存到浏览器,将session保存到请求的服务器,登录时候,将cookie与session进行匹配,匹配的上即为登录成功。如果采取负载均衡轮询等方式,一台服务器有了session,但是另一台服务器上没有session,这就导致登录不上,此时就需要我们采取redis,将session放到redis中,将redis单独放到一个服务器上,每次登录,我们都去这个服务器找session,这样就不会出现cookie与session不匹配而导致登录失败了。

三、会话登录故障场景

1、配置Nginx

[root@Web01 conf.d]# vim php.conf
server {
    listen 80;
    server_name php.koten.com;
    root /code/phpMyAdmin-4.8.4-all-languages;

    location / {
        index index.php index.html;
    }

    location ~ \.php$ {
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
}
[root@Web01 conf.d]# systemctl restart nginx

2、在Web01和Web02分别安装phpmyadmin

[root@Web01 conf.d]# cd /code
[root@Web01 code]# wget https://files.phpmyadmin.net/phpMyAdmin/4.8.4/phpMyAdmin-4.8.4-all-languages.zip
[root@Web01 code]# unzip phpMyAdmin-4.8.4-all-languages.zip

3、配置phpmyadmin连接远程的数据库

[root@Web01 code]# cd phpMyAdmin-4.8.4-all-languages/
[root@Web01 phpMyAdmin-4.8.4-all-languages]# cp config.sample.inc.php config.inc.php
[root@Web01 phpMyAdmin-4.8.4-all-languages]# vim config.inc.php
/* Server parameters */
$cfg['Servers'][$i]['host'] = '172.16.1.51';

4、配置授权

[root@Web01 conf.d]# chown -R www.www /var/lib/php/

5、浏览器访问并登录,获取cookie信息

7389fff03de2499e8324104f75a35fa1.png

5fd4ac3bbccf467b82fd342b0e014805.png

[root@Web01 php]# ll /var/lib/php/session/
total 28
-rw------- 1 www www   36 Apr  8 22:20 sess_24615fce63ea1785689dba62147bf683

6、将Web01上配置好的phpmyadmin和Nginx配置文件推送到Web02上

[root@Web01 code]# scp -rp  phpMyAdmin-4.8.4-all-languages root@172.16.1.8:/code/
[root@Web01 code]# scp /etc/nginx/conf.d/php.conf  root@172.16.1.8:/etc/nginx/conf.d/

7、在web02上重载Nginx服务、授权

[root@Web02 code]# systemctl restart nginx
[root@Web02 code]# chown -R www.www /var/lib/php/

8、接入负载均衡

[root@LB01 conf.d]# vim proxy_php.conf 
upstream php {
        server 172.16.1.7:80;
        server 172.16.1.8:80;
}
server {
        listen 80;
        server_name php.koten.com;
        location / {
                proxy_pass http://php;
                include proxy_params;
        }
}

[root@lb01 conf.d]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
[root@lb01 conf.d]# systemctl restart nginx

9、经过轮询后发现,如果session保存在本地文件,登录不上phpmyadmin

55a3fd1b5a8d4b6a8c7b8ac159c0d4ba.png

四、使用redis解决会话登录问题

1、安装redis内存数据库

[root@MySQL ~]# yum install redis -y

2、配置redis监听在172.16.1.0网段上

[root@MySQL ~]# sed  -i '/^bind/c bind 127.0.0.1 172.16.1.51' /etc/redis.conf

3、启动redis

[root@MySQL ~]# systemctl start redis
[root@MySQL ~]# systemctl enable redis

4、php配置session连接redis

#1.修改/etc/php.ini文件
[root@Web01 ~]# vim /etc/php.ini
session.save_handler = redis
session.save_path = "tcp://172.16.1.51:6379"
;session.save_path = "tcp://172.16.1.51:6379?auth=123" #如果redis存在密码,则使用该方式
session.auto_start = 1

#2.注释php-fpm.d/www.conf里面的两条内容,否则session内容会一直写入/var/lib/php/session目录中
;php_value[session.save_handler] = files
;php_value[session.save_path]    = /var/lib/php/session

5、重启php-fpm

[root@Web01 code]# systemctl restart php-fpm

6、Web01配置推送给Web02

[root@Web01 code]# scp /etc/php.ini root@172.16.1.8:/etc/php.ini  
[root@Web01 code]# scp /etc/php-fpm.d/www.conf root@172.16.1.8:/etc/php-fpm.d/www.conf 

7、Web02重启php-fpm

[root@Web02 code]# systemctl restart php-fpm

8、redis查看数据

[root@MySQL ~]# redis-cli 
127.0.0.1:6379> keys *
1) "PHPREDIS_SESSION:f96f184460e8ca9dfdc65f3e70cca79c"

9、测试登录

登录成功! 

56e5b4443b1d4a2da0fafa6e8b141e14.png

五、多级代理获取真实用户IP地址

 我们的web服务器的日志查看到的是负载均衡的服务器IP,所以我们需要加如下参数去获取真实的用户IP

set_real_ip_from: 真实服务器上一级代理的IP地址或者IP地址段,可以写多行
real_ip_header: 从那个heare头检索出需要的IP地址
real_ip_recursive: 递归排除set_real_ip_from里出现的IP,没有出现的则为remote用户来源IP
server {
    listen 80;
    server_name nginx.koten.com;
    set_real_ip_from 172.16.1.7;
    set_real_ip_from 172.16.1.8;
    real_ip_header X-Forwarded-For;
    real_ip_recursive on;
    location / {
        root /code;
        index index.html index.php;
    }
}

我是koten,10年运维经验,持续分享运维干货,感谢大家的阅读和关注!

  • 3
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

我是koten

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值