day35-负载均衡

1.每日复盘与今日内容

1.1复盘

  • LNMP拆分
  • 扩展多台WEB服务器
  • 静态配置、动态挂载NFS🍟🍟🍟
  • 正向代理、反向代理🍟🍟🍟
  • 负载均衡基础🍟🍟🍟🍟🍟

1.2今日内容

  • 负载均衡
  • 四层和七层的区别
  • 编译安装Nginx、Redis🍟🍟🍟🍟🍟
  • 部署保持会话🍟🍟🍟🍟🍟

2.负载均衡

1.为什么要用负载均衡?

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

2.负载均衡称谓

  • LB-load banlance

3.共有云称呼

SLB 阿里云负载均衡

QLB 青云负载均衡

CLB 腾讯云负载均衡

ULB ucloud负载均衡

...

4.常见的负载均衡软件

Nginx: 只支持七层负载

Haproxy: 只支持七层负载

LVS: 支持四层和七层负载

5.四层和七层的区别

|----|-------|
| 类别 | 特点 |
| 四层 | IP+端口 |
| 七层 | 域名 |

  • LVS: 四种网络模式

    1.DR模式 # 四层、目标地址的改写
    2.NAT # 代理模式 典型的路由NAT
    3.FULL NAT#
    4.TUN # 隧道模式

6.Nginx实现负载均衡

复制代码
Nginx要实现负载均衡需要用到proxy_pass代理模块配置.
Nginx负载均衡与Nginx代理不同地方在于,Nginx的一个location仅能代理一台服务器,而Nginx负载均衡则是将客户端请求代理转发至一组upstream虚拟服务池.
  • WEB01配置静态页面:

    [root@web01 conf.d]# cat www.oldboy.conf
    server {
    listen 80;
    server_name www.oldboy.com;
    root /code/test;
    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]# cat /code/test/index.html
    web01....

  • WEB02配置静态页面:

    [root@web02 conf.d]# cat oldboy.conf
    server {
    listen 80;
    server_name www.oldboy.com;
    root /code/test;
    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 reload nginx
    [root@web02 conf.d]# cat /code/test/index.html
    web02...

  • LB负载均衡配置转发

    [root@lb01 conf.d]# cat lb.conf
    upstream webs {
    server 10.0.0.7;
    server 10.0.0.8;
    }
    server {
    listen 80;
    server_name www.oldboy.com;

    复制代码
      location / {
      proxy_pass http://webs;
      proxy_set_header Host $http_host;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_http_version 1.1;
    
      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 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 reload nginx

  • windows hosts解析

    10.0.0.5 www.oldboy.com

7.负载均衡典型故障

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

|-----|----------------------------------|
| 状态码 | 原因 |
| 500 | 依赖服务(数据库、缓存)突然不可用 |
| 502 | 后端服务崩溃或未启动 |
| 503 | 通常因维护或过载 服务器资源耗尽(CPU、内存、连接数超过限制) |
| 504 | 后端服务处理时间过长(如复杂SQL查询) |

复制代码
1.如果后端web的nginx挂掉自动访问下一台,不需要额外的配置
2.如果后端web的nginx没有挂掉而是PHP或者数据库挂掉,则需要额外配置参数proxy_next_upstream 状态码
[root@lb01 conf.d]# vim lb.conf 
upstream webs {
        server 10.0.0.7;
        server 10.0.0.8;
}
server {
        listen 80;
        server_name www.wp.com;
        #配置遇到以下状态码自动访问下一台server
        proxy_next_upstream error timeout http_500 http_502 http_503 http_504;

        location / {
        proxy_pass http://webs;
        proxy_set_header Host $http_host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_http_version 1.1;

....

8.Nginx的调度算法

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

复制代码
1.默认为轮询
2.加权轮询在后端web服务器硬件配置不相同的情况下使用
[root@lb01 conf.d]# cat lb.conf 
upstream webs {
	server 10.0.0.7 weight=5;	# web01处理5个请求 然后web02处理1个请求
	server 10.0.0.8;
}
...

3.ip_hash 按IP给固定分配到WEB服务器,第一个访问的是web01,以后一直都是web01.
缺点: 会让负载均衡变得不均衡
优点:可以解决会话保持的问题

9.Nginx后端服务状态

复制代码
Nginx负载均衡后端状态
down      # 不参与调度 
backup    # 当其他server挂掉后,backup的server才会参与调度,类似备胎

10.Nginx负载均衡健康检查

1️⃣下载编译过程中用到的命令

复制代码
yum install -y gcc glibc gcc-c++ pcre-devel openssl-devel patch

2️⃣下载Nginx源码包必须和安装过的版本一致

复制代码
wget http://nginx.org/download/nginx-1.26.1.tar.gz

3️⃣下载nginx_upstream_check第三方模块

通过网盘分享的文件:master.zip

链接: 百度网盘 请输入提取码 提取码: 1234

--来自百度网盘超级会员v5的分享

复制代码
上传模块到家目录
[root@lb01 ~]# ll
total 1396
-rw-r--r-- 1 root root  177080 Aug 15 11:17 master.zip
-rw-r--r-- 1 root root 1244738 May 29  2024 nginx-1.26.1.tar.gz
解压代码
[root@lb01 ~]# unzip master.zip
[root@lb01 ~]# tar xf nginx-1.26.1.tar.gz

4️⃣进入nginx目录,打补丁(nginx的版本是1.26补丁就选择1.26相近的,p1代表在nginx目录,p0是不在nginx目录)

复制代码
[root@lb01 nginx-1.26.1]# patch -p1 < ../nginx_upstream_check_module-master/check_1.20.1+.patch

5️⃣./configure配置路径以及模块

  • 作用:它就像是一个 "智能检查员",负责:

检查你的系统环境

检查依赖环境: gcc

如果缺了某个依赖,它会直接报错,而不是让你在 make 时莫名其妙失败。

根据你的系统环境(比如安装路径、CPU架构)生成一个 Makefile 文件,告诉 make 命令如何编译代码。

允许你自定义安装选项

比如你可以通过参数指定安装路径(--prefix=/usr/local)、启用/禁用某些功能(--enable-feature 或 --disable-feature)。

#通过nginx -V 找出默认yum安装的一个配置参数,然后将新的模块添加进去

--add-module=/root/nginx_upstream_check_module-master

复制代码
[root@lb01 nginx-1.26.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 --add-module=/root/nginx_upstream_check_module-master --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'

6️⃣make

复制代码
make:编译源代码,生成可执行文件(如 myapp)。

7️⃣make install

复制代码
make install:把编译好的文件"正式安装"到系统里,让你能直接运行。

8️⃣最后检查是否编译成功

复制代码
[root@lb01 ~]# nginx -V
nginx version: nginx/1.26.1
built by gcc 7.3.0 (GCC) 
built with OpenSSL 1.1.1f  31 Mar 2020
TLS SNI support enabled
configure arguments: --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 --add-module=/root/nginx_upstream_check_module-master --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'
[root@lb01 ~]# 
[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

9️⃣最终的健康状态检查模块配置

复制代码
[root@lb01 conf.d]# vim lb.conf
upstream webs {
    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 {        
        server_name www.oldboy.com;
        proxy_next_upstream error timeout http_500 http_502 http_503 http_504;

        location / {
        proxy_pass http://webs;
        proxy_set_header Host $http_host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_http_version 1.1;

        proxy_connect_timeout 30;
        proxy_send_timeout 60;
        proxy_read_timeout 60;

        proxy_buffering on;
        proxy_buffer_size 32k;
        proxy_buffers 4 128k;
        }

      location /check {	# 当访问www.oldboy.com/check url时则返回状态模块对应的信息
        check_status;
      }

}

🔟浏览器访问测试

复制代码
www.oldboy.com/check

11.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️⃣WEB01部署phpmyadmin业务(用页面管理数据库的业务) 登录会将session保存到WEB本地服务器

复制代码
[root@web01 conf.d]# cat admin.conf
server {
        listen 80;
        server_name www.admin.com;
        root /code/admin;

        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]# 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 /code/admin
[root@web01 conf.d]# cd /code/admin
[root@web01 admin]# 

#上传phpmyadmin代码
[root@web01 admin]# ll
phpMyAdmin-5.2.2-all-languages.zip
[root@web01 admin]# unzip phpMyAdmin-5.2.2-all-languages.zip
[root@web01 admin]# mv phpMyAdmin-5.2.2-all-languages/* .


#将示例配置文件拷贝成生效的配置文件
[root@web01 admin]# cp config.sample.inc.php config.inc.php

#修改数据指向为172.16.1.51
[root@web01 admin]# grep 172.16.1.51 config.inc.php
$cfg['Servers'][$i]['host'] = '172.16.1.51';

#windows hosts解析
10.0.0.7 www.admin.com


#修改存储会话目录的属主和属组为nginx和php的启动用户
[root@web01 admin]# ll -d /var/lib/php/session
drwxrwx--- 2 root apache 6 Mar 31 16:54 /var/lib/php/session
[root@web01 admin]# chown www.www /var/lib/php/session
[root@web01 admin]# ll -d /var/lib/php/session
drwxrwx--- 2 www www 6 Mar 31 16:54 /var/lib/php/session
  • 修改完权限后

2️⃣WEB02部署phpmyadmin服务

复制代码
[root@web02 conf.d]# vim admin.conf
server {
        listen 80;
        server_name www.admin.com;
        root /code/admin;

        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@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 reload nginx

[root@web02 admin]# scp -r 10.0.0.7:/code/admin /code/

[root@web02 admin]# chown www.www /var/lib/php/session
[root@web02 admin]# ll -d /var/lib/php/session
drwxrwx--- 2 www www 6 Mar 31 16:54 /var/lib/php/session

测试:
windows hosts文件 
10.0.0.8 www.admin.com

3️⃣phpmyadmin接入负载均衡

复制代码
[root@lb01 conf.d]# cat admin.conf
upstream admin {
    server 172.16.1.7:80;
    server 172.16.1.8:80;
}
server {
	listen 80;
	server_name www.admin.com;

	location / {
	proxy_pass http://admin;
	proxy_set_header Host $http_host;
	proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
	proxy_http_version 1.1;

	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 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


#windows解析到负载均衡
10.0.0.5 www.admin.com
  • cookie

当用户登录网页时,负载均衡会选择01服务器,输入账号密码,服务器会生成一个cookie短时间记住账号密码,但点击登录的瞬间负载会跳到02服务器上,这时02上没有对应的账号密码,又要重新输入,陷入死循环。此时我们会将cookie放入共享缓存中,每个服务器都可以看到。

12.部署redis

第一步:

复制代码
#安装redis
[root@db01 ~]# yum -y install redis
#修改监听IP
[root@db01 ~]# grep ^bind  /etc/redis.conf
bind 127.0.0.1 172.16.1.51

#设置密码
[root@db01 ~]# grep ^requirepass /etc/redis.conf -n
1044:requirepass 123456

#启动redis
[root@db01 ~]# systemctl start redis
[root@db01 ~]# systemctl enable redis

第二步:

复制代码
#配置PHP session指向redis
web01修改:
[root@web01:~]#vim /etc/php.ini
1222 session.save_handler = redis
1255 session.save_path = "tcp://172.16.1.51:6379?auth=123456"

#注释倒数3和4行
[root@web01 ~]# tail -4 /etc/php-fpm.d/www.conf
;php_value[session.save_handler] = files		        # 这行
;php_value[session.save_path]    = /var/lib/php/session # 这行
php_value[soap.wsdl_cache_dir]  = /var/lib/php/wsdlcache
;php_value[opcache.file_cache]  = /var/lib/php/opcache

第三步:(麒麟不支持redis,所以只能用编译安装)

复制代码
编译PHP 连接redis的插件
PHP安装redis插件
第一步: 下载redis源码包
[root@web01:~]# wget https://pecl.php.net/get/redis-5.3.7.tgz
第二步: 解压代码
[root@web01:~]# tar -zxvf redis-5.3.7.tgz
第三步: 配置
[root@web01:~]#cd redis-5.3.7/
[root@web01 redis-5.3.7]# phpize
[root@web01:redis-5.3.7]#./configure
第四步: 编译安装
[root@web01:redis-5.3.7]# make && make install
第五步: 开启redis插件功能,配置文件增加以下一行内容
[root@web01:~]#grep redis.so /etc/php.ini  -n
1357:extension=redis.so

[root@web01 ~]# php-fpm -t
[15-Aug-2025 16:16:27] NOTICE: configuration file /etc/php-fpm.conf test is successful

第六步: 重启服务
[root@web01:~]#systemctl restart php-fpm

第四步:

复制代码
#WEB02执行WEB01相同的动作
[root@web02 ~]# scp 10.0.0.7:/etc/php.ini /etc/
[root@web02 ~]# scp 10.0.0.7:/etc/php-fpm.d/www.conf /etc/php-fpm.d/
#下面的命令直接复制到web02回车执行
wget https://pecl.php.net/get/redis-5.3.7.tgz
tar -zxvf redis-5.3.7.tgz
cd redis-5.3.7
# 生成 configure 并编译
phpize
./configure
make
sudo make install


#检测是否成功
php-fpm -t
#重启php-fpm生效


#最后测试登录phpmyadmin

3.今日总结

  • 负载均衡
  • 四层和七层的区别
  • 编译安装Nginx、Redis🍟🍟🍟🍟🍟
  • 部署保持会话🍟🍟🍟🍟🍟
相关推荐
杜子不疼.6 分钟前
《Python学习之第三方库:开启无限可能》
开发语言·python·学习
怀刃6 分钟前
C# 内存监控怎么定位问题
运维
TPBoreas7 分钟前
Jenkins启动端口修改失败查找日志
运维·服务器·jenkins
小张的博客之旅1 小时前
宁波市第八届网络安全大赛初赛(REVERSE-Writeup)
学习·网络安全·reverse
正在努力的小河2 小时前
Linux设备树简介
linux·运维·服务器
荣光波比2 小时前
Linux(十一)——LVM磁盘配额整理
linux·运维·云计算
前端世界2 小时前
在鸿蒙里优雅地处理网络错误:从 Demo 到实战案例
网络·华为·harmonyos
墨雨听阁2 小时前
8.18网络编程——基于UDP的TFTP文件传输客户端
网络·网络协议·学习·udp
网络研究院4 小时前
网络安全和基础设施安全局 (CISA) 表示微分段不再是可选的
网络·安全·web安全·零信任·微分段