• 【笔记】Nginx(5)七层负载均衡


    Nginx负载均衡基本概述

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

        往往我们接触的最多的是SLB(Server Load Balance)负载均衡,实现最多的也是SLB、那么SLB它的调度节点和服务节点通常是在一个地域里面。那么它在这个小的逻辑地域里面决定了他对部分服务的实时性、响应性是非常好的。

        所以说当海量用户请求过来以后,它同样是请求调度节点,调度节点将用户的请求转发给后端对应的服务节点,服务节点处理完请求后在转发给调度节点,调度节点最后响应给用户节点。这样也能实现一个均衡的作用,那么Nginx则是一个典型的SLB。

    负载均衡的叫法有很多:

    负载均衡
    负载
    Load Balance
    LB
    
    • 1
    • 2
    • 3
    • 4

    公有云中叫法

    SLB 阿里云负载均衡
    QLB 青云负载均衡
    CLB 腾讯云负载均衡
    ULB ucloud负载均衡
    
    • 1
    • 2
    • 3
    • 4

    常见的负载均衡的软件

    Nginx
    Haproxy
    LVS
    
    • 1
    • 2
    • 3

    在这里插入图片描述

    负载均衡能实现的应用场景一: 四层负载均衡
        所谓四层负载均衡指的是OSI七层模型中的传输层,那么传输层Nginx已经能支持TCP/IP的控制,所以只需要对客户端的请求进行TCP/IP协议的包转发就可以实现负载均衡,那么它的好处是性能非常快、只需要底层进行应用处理,而不需要进行一些复杂的逻辑。
    在这里插入图片描述

    负载均衡能实现的应用场景二:七层负载均衡
        七层负载均衡它是在应用层,那么它可以完成很多应用方面的协议请求,比如我们说的http应用的负载均衡,它可以实现http信息的改写、头信息的改写、安全应用规则控制、URL匹配规则控制、以及转发、rewrite等等的规则,所以在应用层的服务里面,我们可以做的内容就更多,那么Nginx则是一个典型的七层负载均衡SLB
    在这里插入图片描述

    四层负载均衡与七层负载均衡区别
        四层负载均衡数据包在底层就进行了分发,而七层负载均衡数据包则是在最顶层进行分发、由此可以看出,七层负载均衡效率没有四负载均衡高。

        但七层负载均衡更贴近于服务,如:http协议就是七层协议,我们可以用Nginx可以作会话保持,URL路径规则匹配、head头改写等等,这些是四层负载均衡无法实现的。

    注意:四层负载均衡不识别域名,七层负载均衡识别域名

    Nginx负载均衡配置场景

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

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

    在这里插入图片描述

    Nginx upstream虚拟配置语法

    Syntax: upstream name { ... }
    Default: -
    Context: http
    upstream例
    
    • 1
    • 2
    • 3
    • 4
    upstream backend {
        server backend1.example.com       weight=5;
        server backend2.example.com:8080;
        server unix:/tmp/backend3;
        server backup1.example.com:8080   backup;
    }
    server {
        location / {
            proxy_pass http://backend;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    1.环境准备

    角色外网****IP(NAT)内网****IP(LAN)主机名
    LB01eth0:10.0.0.5eth1:172.16.1.5lb01
    web01eth0:10.0.0.7eth1:172.16.1.7web01
    web02eth0:10.0.0.8eth1:172.16.1.8web02

    2.Web01服务器上配置nginx

    [root@web01 conf.d]# cat node.conf 
    server {
    	listen 80;
    	server_name node.ahui.com;
    
    	location / {
    	root /node/;
    	index index.html;
    	}
    }
    
    [root@web01 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@web01 conf.d]# systemctl restart nginx
    
    [root@web01 conf.d]# mkdir /node
    [root@web01 conf.d]# echo web01......... > /node/index.html
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    3.Web02服务器上配置nginx

    [root@web02 conf.d]# cat node.conf 
    server {
    	listen 80;
    	server_name node.ahui.com;
    
    	location / {
    	root /node/;
    	index index.html;
    	}
    }
    
    [root@web02 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@web02 conf.d]# systemctl restart nginx
    
    [root@web02 conf.d]# mkdir /node
    [root@web02 conf.d]# echo web02........ > /node/index.html
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    4.配置Nginx负载均衡

    [root@lb01 conf.d]# cat node.conf 
    upstream node {
    	server  172.16.1.7;
    	server  172.16.1.8:80;
    }
    server {
    	listen 80;
    	server_name node.ahui.com;
    	
    	location / {
    	proxy_pass http://node;
    	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
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    5.准备Nginx负载均衡调度使用的proxy_params

    proxy_set_header Host $http_host;
    proxy_http_version 1.1;
    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;
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    修改hosts文件解析node.ahui.com 到10.0.0.5 通过浏览器访问
    在这里插入图片描述

    在这里插入图片描述

    负载均衡常见典型故障
        如果后台服务连接超时,Nginx是本身是有机制的,如果出现一个节点down掉的时候,Nginx会更据你具体负载均衡的设置,将请求转移到其他的节点上,但是,如果后台服务连接没有down掉,但是返回错误异常码了如:504、502、500,这个时候你需要加一个负载均衡的设置,如下:proxy_next_upstream http_500 | http_502 | http_503 | http_504 |http_404;意思是,当其中一台返回错误码404,500…等错误时,可以分配到下一台服务器程序继续处理,提高平台访问成功率。

    server {
        listen 80;
        server_name www.oldboy.com;
    
        location / {
            proxy_pass http://node;
            proxy_next_upstream error timeout http_500 http_502 http_503 http_504;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    Nginx负载均衡调度算法

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

    Nginx负载均衡[rr]轮询具体配置

    upstream load_pass {
        server 10.0.0.7:80;
        server 10.0.0.8:80;
    }
    
    • 1
    • 2
    • 3
    • 4

    Nginx负载均衡[wrr]权重轮询具体配置

    upstream load_pass {
        server 10.0.0.7:80 weight=5;
        server 10.0.0.8:80;
    }
    
    • 1
    • 2
    • 3
    • 4

    Nginx负载均衡ip_hash
    具体配置不能和weight一起使用。

    #如果客户端都走相同代理, 会导致某一台服务器连接过多
    upstream load_pass {
        ip_hash;
        server 10.0.0.7:80 weight=5;
        server 10.0.0.8:80;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    Nginx负载均衡后端状态

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

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

    测试down状态测试该Server不参与负载均衡的调度

    upstream load_pass {
        #不参与任何调度, 一般用于停机维护
        server 10.0.0.7:80 down;
    }
    
    • 1
    • 2
    • 3
    • 4

    测试backup以及down状态

    upstream load_pass {
        server 10.0.0.7:80 down;
        server 10.0.0.8:80 backup;
        server 10.0.0.9:80 max_fails=1 fail_timeout=10s;
    }
    
    location  / {
        proxy_pass http://load_pass;
        include proxy_params;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

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

    upstream load_pass {
        server 10.0.0.7:80;
        server 10.0.0.8:80 max_fails=2 fail_timeout=10s;
    }
    
    • 1
    • 2
    • 3
    • 4

    测试max_conns最大TCP连接数

    upstream load_pass {
        server 10.0.0.7:80;
        server 10.0.0.8:80 max_conns=1;
    }
    
    • 1
    • 2
    • 3
    • 4

    Nginx负载均衡健康检查

    在Nginx官方模块提供的模块中,没有对负载均衡后端节点的健康检查模块,但可以使用第三方模块。
    nginx_upstream_check_module来检测后端服务的健康状态。

    第三方模块项目地址:TP

    1.安装依赖包

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

    2.下载nginx源码包以及nginx_upstream_check模块第三方模块

    [root@lb01 ~]# wget http://nginx.org/download/nginx-1.22.0.tar.gz
    [root@lb01 ~]# wget https://github.com/yaoweibin/nginx_upstream_check_module/archive/master.zip
    
    • 1
    • 2

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

    [root@lb01 ~]# tar xf nginx-1.22.0.tar.gz
    [root@lb01 ~]# unzip master.zip
    
    • 1
    • 2

    4.进入解压出的nginx-1.22.0目录,打补丁(nginx的版本是1.22补丁就选择1.20.1的,p1代表在nginx目录,p0是不在nginx目录)

    #将模块增加到Nginx
    [root@lb01 ~]# cd nginx-1.22.0
    [root@lb01 nginx-1.22.0]# patch -p1 < ../nginx_upstream_check_module-master/check_1.20.1+.patch 
    [root@lb01 nginx-1.22.0]# ./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  --add-module=/root/nginx_upstream_check_module-master --with-stream_realip_module --with-stream_ssl_module --with-stream_ssl_preread_module --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'
    	
    # 最后执行make 编译安装
    [root@lb01 nginx-1.22.0]# make && make install
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    5.在已有的负载均衡上增加健康检查的功能

    [root@lb01 conf.d]# cat node.conf 
    	upstream node {
    		server  172.16.1.7 max_fails=2 fail_timeout=10s;
    		server  172.16.1.8 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 node.oldboy.com;
    		
    		location / {
    		proxy_pass http://node;
    		include proxy_params;
    		}
    		
    		location /check {
    				 check_status;
    		}
    	}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

    Nginx负载均衡会话保持

    在使用负载均衡的时候会遇到会话保持的问题,可通过如下方式进行解决。
    1.使用nginx的ip_hash,根据客户端的IP,将请求分配到对应的IP上
    2.基于服务端的session会话共享(NFS,MySQL,memcache,redis,file)

    在解决负载均衡绘画问题,我们需要了解session和cookie的区别。
    浏览器端存的是cookie每次浏览器发请求到服务端时,报文头是会自动添加cookie信息的。
    服务端会查询用户的cookie作为key去存储里找对应的value(session)
    同意域名下的网站的cookie都是一样的,所以无论几台服务器,无论请求分配到哪一台服务器上同一用户的cookie是不变的。也就是说cookie对应的session也是唯一的。所以,这里只要保证多台业务服务器访问同一个共享存储服务器(NFS,MySQL,memcache,redis,file)就行了。

    1.配置Nginx

    [root@web01 conf.d]# cat php.conf
    server {
        listen 80;
        server_name php.ahui.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
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    2.安装phpmyadmin (web01和web02上都装)

    [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
    
    • 1
    • 2
    • 3

    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';
    
    • 1
    • 2
    • 3
    • 4
    • 5

    4.配置授权

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

    使用浏览器访问页面,获取cookie信息

    在这里插入图片描述

    [root@web01 ~]#ll /val/lib/php/session/
    总用量 4
    -rw-------. 1 www www 2424 821 18:41	sess_a4b63126ccb57be6663edcd2ec8a89d8
    
    • 1
    • 2
    • 3

    5.将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/
    
    • 1
    • 2

    6.在web02上重载Nginx服务

    [root@web02 code]# systemctl restart nginx
    
    • 1

    7.授权

    [root@web02 code]# chown -R www.www /var/lib/php/
    
    • 1

    8.接入负载均衡

    [root@lb01 conf.d]# vim proxy_php.com.conf 
    upstream php {
            server 172.16.1.7:80;
            server 172.16.1.8:80;
    }
    server {
            listen 80;
            server_name php.ahui.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
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    使用负载均衡的轮询功能之后,会发现,如果将session保存在本地文件的话,永远都登录不上去php.oldboy.com

    在这里插入图片描述

    使用redis解决会话登录问题

    1.安装redis内存数据库

    [root@db01 ~]# yum install redis -y
    
    • 1

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

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

    3.启动redis

    [root@db01 ~]# systemctl start redis
    [root@db01 ~]# systemctl enable redis
    
    • 1
    • 2

    4.php配置session连接redis

    #1.修改/etc/php.ini文件
    [root@web ~]# 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
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    5.重启php-fpm

    [root@web01 code]# systemctl restart php-fpm
    
    • 1

    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 
    
    • 1
    • 2

    5.上web02上重启php-fpm

    [root@web02 code]# systemctl restart php-fpm
    
    • 1

    6.redis查看数据

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

    在这里插入图片描述

    多级代理获取真实用户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.oldboy.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;
    	}
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
  • 相关阅读:
    解决github打开慢的问题
    5A同步整流芯片 20V转12V2A/5V4.5A大电流 24W大功率同步整流芯片 大电流降压IC FS2462
    一颗完整意义的LPWAN SOC无线通信芯片——ASR6601
    【Java-Web】利用Session和Filter进行权限管理
    如何给在 SAP Business Application Studio 里开发的 OData 服务准备测试数据试读版
    Camtasia2023简单易用的电脑录屏视频剪辑软件
    docker自动构建jar镜像,自动发布最新镜像的简单shell脚本
    macbook 从0开始下载git/nvm
    C++的奇妙之旅
    DBOW概要理解与记录
  • 原文地址:https://blog.csdn.net/AHui_CSDN/article/details/125411624