1、四层负载均衡

1.1 what

四层负载均衡基于传输层协议包来封装的(如:TCP/IP),七层是指的应用层,它的组装在四层基础之上,无论四层还是七层都是指的OSI网络模型。

1.2 应用场景

  1. 四层+七层来作负载均衡,4层可以保证7层的负载均衡的高可用性。如:nginx就无法保证自己的服务高可用,需要依赖lvs、F5或者keepalive来作。
  2. 如:tcp协议的负载均衡,有些请求是TCP协议的(mysql、ssh),或者说这些请求只需要使用4层进行端口的转发就可以了,所以使用4层负载均衡。

    1.3 四层+七层

    6、负载均衡 - 图1

    1.4 总结

  3. 四层负载均衡仅能转发TCP/IP协议、UDP协议,通常用来转发端口,如: tcp/3306,tcp/22,udp/53。

  4. 四层负载均衡可以用来解决七层负载均衡的端口限制问题。(七层负载均衡最大使用65535个端口号)
  5. 可以用来解决七层负载均衡的高可用问题。(多台后端七层负载均衡能同时的使用)
  6. 四层的转发效率比七层的高的多,但仅支持tcp/ip协议,不支持http或者https协议

    1.5 场景实践

    Nginx配置四层负载均衡
    1.通过访问负载均衡的5555端口,实际是后端的web01的22端口在提供服务。
    2.通过访问负载均衡的6666端口,实际是后端的mysql的3306端口在提供服务。
    1.Nginx四层负载均衡配置语法

    1. stream {
    2. upstream backend {
    3. hash $remote_addr consistent;
    4. server backend1.example.com:12345 weight=5;
    5. server 127.0.0.1:12345 max_fails=3 fail_timeout=30s;
    6. server unix:/tmp/backend3;
    7. }
    8. server {
    9. listen 12345;
    10. proxy_connect_timeout 1s;
    11. proxy_timeout 3s;
    12. proxy_pass backend;
    13. }
    14. }

    2.Nginx四层负载均衡实战

    [root@lb01 ~]# mkdir -p /etc/nginx/conf.c
    [root@lb01 ~]# vim /etc/nginx/nginx.conf
    # 在events层下面,http层上面配置include
    include  /etc/nginx/conf.c/*.conf;
    # 编写四层代理配置
    [root@lb01 ~]# cd /etc/nginx/conf.c/
    [root@lb01 conf.c]# cat stream.conf 
    stream {
     #1.定义虚拟资源池
     upstream ssh {
         server 172.16.1.7:22;
     }
     upstream mysql {
         server 172.16.1.51:3306;
     }
     #2.调用虚拟资源池
     server {
         listen 5555;
         proxy_connect_timeout 1s;
         proxy_timeout 300s;
         proxy_pass ssh;
     }
     server {
         listen 6666;
         proxy_connect_timeout 1s;
         proxy_timeout 300s;
         proxy_pass mysql;
     }
    }
    [root@lb01 conf.c]# systemctl restart nginx
    

    3.如何记录四层负载均衡日志,四层负载均衡日志必须配置在stream模块

    [root@lb01 ~]# cat /etc/nginx/conf.c/tcp_proxy.conf
    stream {
    #定义日志的格式
    log_format  proxy '$remote_addr -  [$time_local]  $status $protocol'
                   '"$upstream_addr" "$upstream_bytes_sent" "$upstream_connect_time"' ;
     #调用日志,使用proxy格式
     access_log /var/log/nginx/tcp_proxy.log proxy;
    
     upstream ssh {
         server 172.16.1.7:22;
     }
     server {
         listen 5555;
         proxy_pass ssh;
     }
    }
    

    2、七层负载均衡

    2.1 基本概述

    为什么需要使用负载均衡

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

6、负载均衡 - 图2

往往我们接触的最多的是SLB(Server Load Balance)负载均衡,实现最多的也是SLB、那么SLB它的调度节点和服务节点通常是在一个地域里面。那么在这个小的逻辑地域里面决定了他对部分服务的实时性、响应性是非常好的。
所以说当海量用户请求过来以后,它同样是请求调度节点,调度节点将用户的请求转发给后端对应的服务节点,服务节点处理完请求后在转发给调度节点,调度节点最后响应给用户节点。这样也能实现一个均衡的作用,那么Nginx则是一个典型的SLB

6、负载均衡 - 图3

负载均衡能实现的应用场景一: 四层负载均衡

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

6、负载均衡 - 图4

负载均衡能实现的应用场景二: 七层负载均衡

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

6、负载均衡 - 图5

四层负载均衡与七层负载均衡区别

四层负载均衡数据包在底层就进行了分发,而七层负载均衡数据包则是在最顶层进行分发、由此可以看出,七层负载均衡效率没有四负载均衡高。
但七层负载均衡更贴近于服务,如:http协议就是七层协议,我们可以用Nginx可以作会话保持,URL路径规则匹配、head头改写等等,这些是四层负载均衡无法实现的。

2.2 配置场景

Nginx要实现负载均衡需要用到proxy_pass代理模块配置.
Nginx负载均衡与Nginx反向代理区别:

  • 反向代理:服务器是需要存储资源的,让用户更快速的接收到资源
  • 负载均衡:为了保证后端web服务器的高可用,高并发,是不需要要存储资源,只需要转发用户的请求。


    6、负载均衡 - 图6

    Nginx upstream虚拟配置语法 ``` Syntax: upstream name { … } Default: - Context: http

upstream 示例

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


<br />_0.环境规划_
| 角色 | 外网IP(NAT) | 内网IP(LAN) | 主机名 |
| --- | --- | --- | --- |
| LB01 | eth0:10.0.0.5 | eth1:172.16.1.5 | lb01 |
| web01 | eth0:10.0.0.7 | eth1:172.16.1.7 | web01 |
| web02 | eth0:10.0.0.8 | eth1:172.16.1.8 | web02 |

_1.Web01服务器上配置nginx, 并创建对应_`_html_`_文件_

[root@web01 ~]# cd /etc/nginx/conf.d/ [root@web01 conf.d]# cat node.conf server { listen 80; server_name node.oldboy.com; location / { root /node; index index.html; } } [root@web01 conf.d]# mkdir /node [root@web01 conf.d]# echo “Web01…” > /node/index.html [root@web01 conf.d]# systemctl restart nginx

_2.Web02服务器上配置nginx, 并创建对应_`_html_`_文件_

[root@web02 ~]# cd /etc/nginx/conf.d/ [root@web02 conf.d]# cat node.conf server { listen 80; server_name node.oldboy.com; location / { root /node; index index.html; } } [root@web02 conf.d]# mkdir /node [root@web02 conf.d]# echo “Web02…” > /node/index.html [root@web02 conf.d]# systemctl restart nginx

_3.配置_`_Nginx_`_负载均衡_

[root@lb01 ~]# cd /etc/nginx/conf.d/ [root@lb01 conf.d]# cat node_proxy.conf upstream node { server 172.16.1.7:80; server 172.16.1.8:80; } server { listen 80; server_name node.oldboy.com; location / { proxy_pass http://node; include proxy_params; } } [root@lb01 conf.d]# systemctl restart nginx

_4.准备_`_Nginx_`_负载均衡调度使用的_`_proxy_params_`

[root@Nginx ~]# 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;

_5.使用浏览器访问_`_node.oldboy.com_`_, 然后不断刷新测试_<br /> <br />![](https://cdn.nlark.com/yuque/0/2021/jpeg/276796/1615120099461-6fa1df96-ac9b-43b1-9bd5-eafa34c215df.jpeg#height=544&id=UKiv0&originHeight=544&originWidth=1282&originalType=binary&size=0&status=done&style=none&width=1282)<br /> <br /> <br />![](https://cdn.nlark.com/yuque/0/2021/jpeg/276796/1615120099198-5a86f8ff-1760-4928-a941-8d8bd602fbff.jpeg#height=544&id=iEISn&originHeight=544&originWidth=1282&originalType=binary&size=0&status=done&style=none&width=1282)
<a name="odJtG"></a>
## 3.3 调度算法
| 调度算法 | 第三方模块 | 概述 |
| --- | --- | --- |
| 轮询(默认) |  | 按时间顺序逐一分配到不同的后端服务器 |
| weight |  | 加权轮询,weight值越大,分配到的访问几率越高 |
| ip_hash |  | 按访问IP的hash结果分配,这样来自同一IP的固定访问一个后端服务器 |
| url_hash | ngx_http_upstream_hash_module | 按照访问URL的hash结果来分配请求,是每个URL定向到同一个后端服务器 |
| fail | upstream_fair | 根据后端服务器的响应时间来分配请求,响应时间短的优先分配 |
| least_conn |  | 最少链接数,那个机器链接数少就分发<br />适用于客户端与后端服务器需要保持长连接的业务 |

轮询

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=1; server 10.0.0.8:80 weight=2; server 10.0.0.9:80 weight=3; }

fail

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

least_conn

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

}

<a name="S5Np0"></a>
### 3.3.1 ip_hash
> “Session 不共享问题:
> 假设用户已经登录过,此时发出的请求被分配到了 A 服务器,但 A 服务器突然宕机,用户的请求则会被转发到 B 服务器。但由于 Session 不共享,B 服务器无法直接读取用户的登录信息来继续执行其他操作。

ip_hash

保证同 IP 发出的请求映射到同一服务器

或者具有相同 hash 值的不同 IP 发出的请求映射到同一服务器

该算法在一定程度上解决了集群部署环境下 Session 不共享的问题(解决会话保持)。

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

利用 `ip_hash`实现其他一些功能:

- **灰度发布:**指上了某服务的新版本,出于降低新版本带来的风险的考虑,想将一部分请求打到老版本的服务上,剩下的打到新版本的服务上。利用ip_hash可以将特定的一系列ip的请求打到特定的服务器上的特性,将那些无关紧要或者内部用户的请求打到新版本服务上,VIP客户的请求打到老版本服务上。
- **文件分段上传:**指当上传的文件很大,比如1G等,只能将该文件拆分成若干小段上传,上传后再重新合并成完整的原文件。各大云厂商的Iaas云服务里的对象存储服务都是实现了对象多段上传的。利用 `ip_hash` 进行文件的分片上传,它可以保证同客户端发出的文件切片最终转发到同一服务器上,利于其接收所有切片后进行合并操作。
<a name="dniHk"></a>
### 3.3.2 url_hash
相同 URL 的请求会分配给固定的服务器,当存在缓存的时候效率一般较高(下次相同url请求来的时候直接走缓存返回而不走后端数据库或者其他微服务)<br />Nginx 默认不支持这种负载均衡算法,需要依赖第三方库`ngx_http_upstream_hash_module`。

server语句中不能写入weight等其他的参数

upstream xxx_server_name{ server 192.168.10.1:80; server 192.168.10.2:80; server 192.168.10.3:80; hash $request_uri; hash_method crc32; # hash算法 }

<a name="L6vSK"></a>
## 3.4 后端状态
后端`Web`服务器在前端`Nginx`负载均衡调度中的状态
| 状态 | 概述 |
| --- | --- |
| down | 当前的server暂时不参与负载均衡 |
| backup | 预留的备份服务器 |
| max_fails | 允许请求失败的次数 |
| fail_timeout | 经过max_fails失败后, 服务暂停时间 |
| max_conns | 限制最大的接收连接数 |

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

<a name="Y9NHB"></a>
## 3.5 健康检查
在Nginx官方模块提供的模块中,没有对负载均衡后端节点的健康检查模块,但可以使用第三方模块nginx_upstream_check_module来检测后方服务的健康状态 [upstream_check_module ](https://github.com/yaoweibin/nginx_upstream_check_module/)<br />项目地址[: https://github.com/yaoweibin/nginx_upstream_check_module/](https://github.com/yaoweibin/nginx_upstream_check_module/)

1.安装依赖包
```bash
yum install -y gcc glibc gcc-c++ prce-devel openssl-devel pcre-devel patch

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

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

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

[root@lb02 ~]# tar xf nginx-1.14.2.tar.gz
[root@lb02 ~]# unzip master.zip

4.进入nginx目录,打补丁(nginx的版本是1.14补丁就选择1.14的,p1代表在nginx目录,p0是不在nginx目录)

[root@lb02 ~]# cd nginx-1.14.2/
[root@lb02 nginx-1.14.2]# patch -p1 <../nginx_upstream_check_module-master/check_1.14.0+.patch

5.编译Nginx,需要添加upstream_check第三方模块

[root@lb02 nginx-1.14.2]# ./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.14.2]# make && make install

6.配置nginx负载均衡,同时打开upstream健康检查功能

[root@lb02 conf.d]# cat proxy.blog.bgx.com.conf
upstream blog.bgx.com {
    server 172.16.1.7:80;
    server 172.16.1.8:80;
    check interval=3000 rise=2 fall=3 timeout=1000 type=tcp;
    #interval检测间隔时间,单位为毫秒
    #rsie表示请求2次正常,标记此后端的状态为up
    #fall表示请求3次失败,标记此后端的状态为down
    #type  类型为tcp
    #timeout为超时时间,单位为毫秒
}
server {
    listen 80;
    server_name blog.bgx.com;
    location / {
        proxy_pass http://blog.bgx.com;
        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;
    }
    location /upstream_status {
        check_status;     #开启upstream状态页面
    }
}

7.通过访问域名/upstream_status则能打开状态页面
6、负载均衡 - 图7
8.尝试关闭一台后端的webserver,再次打开检查见面
6、负载均衡 - 图8

3.6 会话共享

解决会话保持

在使用负载均衡的时候会遇到会话保持的问题,可通过如下方式进行解决

  • 使用nginx的ip_hash,根据客户端的来源IP,将请求分配到相同服务器上
  • 基于服务端的Session会话共享(mysql/memcache/redis/file)

了解session和cookie

  1. 用户第一次请求服务端网站时,服务端会生成对应的session_id,然后存储至客户端浏览器的cookie中。
  2. 客户端尝试登陆服务端网站时,浏览器的请求头自动携带cookie信息,在cookie信息中保存的则是session_id。
  3. 客户端登陆服务端网站后,服务端会将session_id存储在本地文件中, 当用户下次请求网站时会去查询用户提交的cookie作为key去存储里找对应的value(session)

注意: 同一域名下的网站登陆后cookie都是一样的。所以无论负载后端有几台服务器,无论请求分配到哪一台服务器上同一用户的cookie是不会发生变化的。也就是说cookie对应的session也是唯一的。所以,这里只要保证多台业务服务器访问同一个共享服务器(memcache/redis/mysql/file)就行了。

1.首先在多台web上都安装并配置phpmyadmin

#1.安装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
#2.配置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';

2.在多台web上准备phpmyadmin的nginx配置文件

[root@web01 ~]# cat /etc/nginx/conf.d/php.conf
server {
    listen 80;
    server_name php.oldboy.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;
    }
}
#重启Nginx服务
[root@web01 ~]# systemctl restart nginx

3.配置负载均衡服务,调度到后端两台web节点

[root@lb01 ~]# cat /etc/nginx/conf.d/proxy_php.com.conf 
upstream php {
        server 172.16.1.7:80;
        server 172.16.1.8:80;
}
server {
        listen 80;
        server_name php.oldboy.com;
        location / {
                proxy_pass http://php;
                include proxy_params;
        }
}
#检查语法并重启nginx
[root@lb01 conf.d]# nginx -t
[root@lb01 conf.d]# systemctl restart nginx

4.准备redis内存数据库存储session会话

#1.安装redis内存数据库
[root@db01 ~]# yum install redis -y
#2.配置redis监听在172.16.1.0网段上
[root@db01 ~]# sed  -i '/^bind/c bind 127.0.0.1 172.16.1.51' /etc/redis.conf
#3.启动redis
[root@db01 ~]# systemctl start redis
[root@db01 ~]# systemctl enable redis

5.配置php连接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存在密码,则使用该方式
#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

6.使用浏览器登陆网站,获取对应的cookie信息
6、负载均衡 - 图9
7.检查redis中是否存在cookie对应的session

172.16.1.51:6379> keys *
1) "PHPREDIS_SESSION:393ff522ed2a7e26ba44f6d925f991f2"
172.16.1.51:6379>

8.此时用户的cookie始终都不会发生任何变化,无论请求被负载调度到那一台后端web节点服务器都不会出现没有登陆情况
6、负载均衡 - 图10