找回密码
 立即注册
首页 业界区 安全 nginx实现负载均衡和动静分离

nginx实现负载均衡和动静分离

怃膝镁 2025-6-1 18:44:08
负载均衡概述

负载均衡是一种分布式计算技术,用于将网络流量和用户请求分散到多台服务器上,以此来提高网络服务的可用性和可靠性。它通过优化资源使用、最大化吞吐量以及最小化响应时间,增强了网络、服务器和数据中心的伸缩性和灵活性。
Nginx的负载均衡功能主要通过其反向代理模式实现。当客户端发送请求到Nginx服务器时,Nginx会根据预设的负载均衡策略将请求转发给后端服务器,并将后端服务器的响应返回给客户端。Nginx作为代理服务器,有效地分摊了请求压力,提高了系统的处理能力。
Nginx的负载均衡分为七层负载和四层负载,七层负载是指OSI网络模型中的第七层,对应的是HTTP请求。而四层负载对应的是OSI网络模型中的第四层,对应的是IP+PORT。
负载均衡的目的


  • 提高可用性:通过将请求分散到多个服务器,即使部分服务器出现故障,整个系统仍然可以继续提供服务。
  • 增强性能:负载均衡可以提高系统处理大量并发请求的能力,从而提升整体性能。
  • 故障转移:当一台服务器发生故障时,负载均衡器可以自动将流量转移到其他健康的服务器上,以避免服务中断。
  • 降低延迟:通过选择最佳的服务器来处理请求,减少数据传输的延迟。
  • 资源优化:合理分配请求到各个服务器,避免某些服务器过载而其他服务器空闲,优化资源使用。
Nginx的负载均衡调度算法


  • 轮询(Round Robin)
    轮询是 Nginx 默认的负载均衡算法。它按照顺序依次将请求分配给后端服务器,不考虑服务器的当前负载和响应时间。
  • 加权轮询(Weighted Round Robin)
    加权轮询是轮询算法的一个变体,它允许为每个服务器分配重权。权重损失的服务器将接收到更多的请求。这种方法可以根据服务器的性能和负载情况动态调整负载分配。
  • 最少连接数(Least Connections)
    最少连接数算法会将请求分配给当前连接数最少的服务器。这种算法适用于后端服务器性能差异不大的情况。
  • 加权最少连接数(Weighted Least Connections)
    加权最少连接数算法在最少连接数的基础上引入了权重的概念。权重值越高的服务器,会优先分配更多的请求。
  • IP哈希(IP Hash)
    IP 哈希算法会根据客户端的 IP 地址进行哈希计算,将请求分配到固定的后端服务器。这种算法可以实现会话保持,即同一个客户端的请求总是被分配到同一个后端服务器。
  • URL哈希(URL Hash)
    URL 哈希算法会根据请求的 URL 进行哈希计算,将请求分配到固定的后端服务器。这种算法同样可以实现会话保持,适用于基于 URL 的会话管理。
  • 随机(Random)
    随机算法会随机选择一个后端服务器来处理请求。这种算法简单且不考虑服务器的负载情况。
  • 公平(Fair)
    公平算法会根据后端服务器的响应时间来分配请求,响应时间越短的服务器会优先分配更多的请求。这种算法需要安装额外的模块(如 ngx_http_upstream_fair_module)。
七层负载均衡实现

环境信息

IP作用系统规格10.0.0.10lb-负载均衡服务器Ubuntu22.042c4g10.0.0.20web-nginx服务器Ubuntu22.042c4g10.0.0.21web-nginx服务器Ubuntu22.042c4gnginx服务器操作

所有nginx服务器操作这一次即可
10.0.0.20服务器配置网页和nginx配置文件
  1. [root@master ~]# mkdir -p /data/nginx/lb
  2. [root@master ~]# echo '<h1>10.0.0.20<h1/>' >> /data/nginx/lb/index.html
  3. [root@master ~]# cat /etc/nginx/conf.d/lb.conf
  4. server{
  5.   listen 1999;
  6.   server_name _;
  7.   root /data/nginx/lb;
  8.   location / {
  9.    index index.html;
  10.   }
  11. }
  12. [root@master ~]# nginx -t
  13. nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
  14. nginx: configuration file /etc/nginx/nginx.conf test is successful
  15. [root@master ~]# nginx -s reload
复制代码
10.0.0.21服务器配置网页和nginx配置文件
  1. [root@master ~]# mkdir -p /data/nginx/lb
  2. [root@master ~]# echo '<h1>10.0.0.21<h1/>' >> /data/nginx/lb/index.html
  3. [root@master ~]# cat /etc/nginx/conf.d/lb.conf
  4. server{
  5.   listen 1999;
  6.   server_name _;
  7.   root /data/nginx/lb;
  8.   location / {
  9.    index index.html;
  10.   }
  11. }
  12. [root@master ~]# nginx -t
  13. nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
  14. nginx: configuration file /etc/nginx/nginx.conf test is successful
  15. [root@master ~]# nginx -s reload
复制代码
轮询实操配置

轮询是 Nginx 默认的负载均衡算法。它按照顺序依次将请求分配给后端服务器,不考虑服务器的当前负载和响应时间。
10.0.0.10服务器中操作
  1. [root@lb ~]# cat /etc/nginx/conf.d/lb.conf
  2. #upstream模块,实现负载均衡和反向代理的核心组件,upstream的名称,也就是lb字段,在同一个nginx服务器中不能重复
  3. upstream lb {
  4.   server 10.0.0.20:1999;
  5.   server 10.0.0.21:1999;
  6. }
  7. server {
  8.   listen 1999;
  9.   server_name lb.huangSir-devops.com;
  10.   location / {
  11.     proxy_pass http://lb;
  12.     #转发客户端请求的域名
  13.     proxy_set_header Host $http_host;
  14.     #记录客户端请求的真实IP地址
  15.     proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  16.     proxy_set_header X-Real-Ip $remote_addr;
  17.   }
  18. }
  19. [root@lb ~]# nginx -t
  20. nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
  21. nginx: configuration file /etc/nginx/nginx.conf test is successful
  22. [root@lb ~]# nginx -s reload
复制代码
使用curl命令测试访问,可以发现后端服务器在20和21之间轮询
  1. [root@lb ~]# curl 10.0.0.10:1999 -H lb.huangSir-devops.com
  2. <h1>10.0.0.20<h1/>
  3. [root@lb ~]# curl 10.0.0.10:1999 -H lb.huangSir-devops.com
  4. <h1>10.0.0.21<h1/>
  5. [root@lb ~]# curl 10.0.0.10:1999 -H lb.huangSir-devops.com
  6. <h1>10.0.0.20<h1/>
  7. [root@lb ~]# curl 10.0.0.10:1999 -H lb.huangSir-devops.com
  8. <h1>10.0.0.21<h1/>
复制代码
加权轮询配置

加权轮询是轮询算法的一个变体,它允许为每个服务器分配重权。权重损失的服务器将接收到更多的请求。这种方法可以根据服务器的性能和负载情况动态调整负载分配。使用weight指令设置权重,权重值越高,分配到的请求越多,默认权重为1
10.0.0.10服务器中操作:
  1. [root@lb ~]# cat /etc/nginx/conf.d/lb_weight.conf
  2. upstream lb_weight {
  3.   server 10.0.0.20:1999 weight=1;
  4.   server 10.0.0.21:1999 weight=2;
  5. }
  6. server {
  7.   listen 2999;
  8.   server_name lb.huangSir-devops.com;
  9.   location / {
  10.     proxy_pass http://lb_weight;
  11.     #转发客户端请求的域名
  12.     proxy_set_header Host $http_host;
  13.     #记录客户端请求的真实IP地址
  14.     proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  15.     proxy_set_header X-Real-Ip $remote_addr;
  16.   }
  17. }
  18. [root@lb ~]# nginx -t
  19. nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
  20. nginx: configuration file /etc/nginx/nginx.conf test is successful
  21. [root@lb ~]# nginx -s reload
复制代码
使用curl命令测试访问,经过测试发现,20和21服务器之间是会进行1:2的次数出现
  1. [root@lb ~]# curl 10.0.0.10:2999 -H lb.huangSir-devops.com
  2. <h1>10.0.0.20<h1/>
  3. [root@lb ~]# curl 10.0.0.10:2999 -H lb.huangSir-devops.com
  4. <h1>10.0.0.21<h1/>
  5. [root@lb ~]# curl 10.0.0.10:2999 -H lb.huangSir-devops.com
  6. <h1>10.0.0.21<h1/>
  7. [root@lb ~]# curl 10.0.0.10:2999 -H lb.huangSir-devops.com
  8. <h1>10.0.0.20<h1/>
  9. [root@lb ~]# curl 10.0.0.10:2999 -H lb.huangSir-devops.com
  10. <h1>10.0.0.21<h1/>
  11. [root@lb ~]# curl 10.0.0.10:2999 -H lb.huangSir-devops.com
  12. <h1>10.0.0.21<h1/>
复制代码
最少连接数配置

最少连接数算法会将请求分配给当前连接数最少的服务器。这种算法适用于后端服务器性能差异不大的情况。
最少连接数配置使用least_conn指令进行配置
10.0.0.10服务器中操作:
  1. [root@lb ~]# cat /etc/nginx/conf.d/lb_least_conn.conf
  2. upstream lb_least_conn {
  3.   least_conn;
  4.   server 10.0.0.20:1999;
  5.   server 10.0.0.21:1999;
  6. }
  7. server {
  8.   listen 3999;
  9.   server_name lb.huangSir-devops.com;
  10.   location / {
  11.     proxy_pass http://lb_least_conn;
  12.     #转发客户端请求的域名
  13.     proxy_set_header Host $http_host;
  14.     #记录客户端请求的真实IP地址
  15.     proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  16.     proxy_set_header X-Real-Ip $remote_addr;
  17.   }
  18. }
  19. [root@lb ~]# nginx -t
  20. nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
  21. nginx: configuration file /etc/nginx/nginx.conf test is successful
  22. [root@lb ~]# nginx -s reload
复制代码
在10机器上使用ab命令进行测试访问,然后查看后面代理的两台服务器的请求日志
  1. [root@lb ~]# apt update -y
  2. [root@lb ~]# apt install apache2-utils -y
  3. #-n 100:发送 100 个请求。-c 10:并发数为 10。
  4. [root@lb ~]# ab -n 100 -c 10 http://lb.huangSir-devops.com:3999/
  5. This is ApacheBench, Version 2.3 <$Revision: 1879490 $>
  6. Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
  7. Licensed to The Apache Software Foundation, http://www.apache.org/
  8. Benchmarking lb.huangSir-devops.com (be patient).....done
  9. Server Software:        nginx/1.18.0
  10. Server Hostname:        lb.huangSir-devops.com
  11. Server Port:            3999
  12. Document Path:          /
  13. Document Length:        19 bytes
  14. Concurrency Level:      10
  15. Time taken for tests:   0.023 seconds
  16. Complete requests:      100
  17. Failed requests:        0
  18. Total transferred:      25900 bytes
  19. HTML transferred:       1900 bytes
  20. Requests per second:    4287.98 [#/sec] (mean)
  21. Time per request:       2.332 [ms] (mean)
  22. Time per request:       0.233 [ms] (mean, across all concurrent requests)
  23. Transfer rate:          1084.56 [Kbytes/sec] received
  24. Connection Times (ms)
  25.               min  mean[+/-sd] median   max
  26. Connect:        0    0   0.3      0       2
  27. Processing:     1    2   0.4      2       3
  28. Waiting:        0    2   0.5      2       3
  29. Total:          1    2   0.4      2       4
  30. Percentage of the requests served within a certain time (ms)
  31.   50%      2
  32.   66%      2
  33.   75%      2
  34.   80%      2
  35.   90%      3
  36.   95%      3
  37.   98%      3
  38.   99%      4
  39. 100%      4 (longest request)
复制代码
加权最少连接数配置

加权最少连接数算法在最少连接数的基础上引入了权重的概念。权重值越高的服务器,会优先分配更多的请求。
最少连接数配置使用least_conn和weight指令进行配置
10.0.0.10服务器中操作:
  1. [root@lb ~]# cat /etc/nginx/conf.d/lb_least_weight.conf
  2. upstream lb_least_weight {
  3.   least_conn;
  4.   server 10.0.0.20:1999 weight=1;
  5.   server 10.0.0.21:1999 weight=2;
  6. }
  7. server {
  8.   listen 4999;
  9.   server_name lb.huangSir-devops.com;
  10.   location / {
  11.     proxy_pass http://lb_least_weight;
  12.     #转发客户端请求的域名
  13.     proxy_set_header Host $http_host;
  14.     #记录客户端请求的真实IP地址
  15.     proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  16.     proxy_set_header X-Real-Ip $remote_addr;
  17.   }
  18. }
  19. [root@lb ~]# nginx -t
  20. nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
  21. nginx: configuration file /etc/nginx/nginx.conf test is successful
  22. [root@lb ~]# nginx -s reload
复制代码
测试过程略
IP哈希配置

IP 哈希算法会根据客户端的 IP 地址进行哈希计算,将请求分配到固定的后端服务器。这种算法可以实现会话保持,即同一个客户端的请求总是被分配到同一个后端服务器。
IP哈希使用ip_hash指令进行配置
10.0.0.10服务器中操作:
  1. [root@lb ~]# cat /etc/nginx/conf.d/lb_ip.conf
  2. upstream lb_ip {
  3.   #指定ip_hash负载算法
  4.   ip_hash;
  5.   server 10.0.0.20:1999;
  6.   server 10.0.0.21:1999;
  7. }
  8. server {
  9.   listen 5999;
  10.   server_name lb.huangSir-devops.com;
  11.   location / {
  12.     proxy_pass http://lb_ip;
  13.     #转发客户端请求的域名
  14.     proxy_set_header Host $http_host;
  15.     #记录客户端请求的真实IP地址
  16.     proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  17.     proxy_set_header X-Real-Ip $remote_addr;
  18.   }
  19. }
  20. [root@lb ~]# nginx -t
  21. nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
  22. nginx: configuration file /etc/nginx/nginx.conf test is successful
  23. [root@lb ~]# nginx -s reload
复制代码
使用curl测试,可以发现连接的服务器都是21
  1. [root@lb ~]# cat /etc/nginx/conf.d/lb_ip.conf
  2. upstream lb_ip {
  3.   ip_hash;
  4.   server 10.0.0.20:1999;
  5.   server 10.0.0.21:1999;
  6. }
  7. server {
  8.   listen 5999;
  9.   server_name lb.huangSir-devops.com;
  10.   location / {
  11.     proxy_pass http://lb_ip;
  12.     #转发客户端请求的域名
  13.     proxy_set_header Host $http_host;
  14.     #记录客户端请求的真实IP地址
  15.     proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  16.     proxy_set_header X-Real-Ip $remote_addr;
  17.   }
  18. }
  19. [root@lb ~]# nginx -t
  20. nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
  21. nginx: configuration file /etc/nginx/nginx.conf test is successful
  22. [root@lb ~]# nginx -s reload
  23. [root@lb ~]# curl 10.0.0.10:5999 -H lb.huangSir-devops.com
  24. <h1>10.0.0.21<h1/>
  25. [root@lb ~]# curl 10.0.0.10:5999 -H lb.huangSir-devops.com
  26. <h1>10.0.0.21<h1/>
  27. [root@lb ~]# curl 10.0.0.10:5999 -H lb.huangSir-devops.com
  28. <h1>10.0.0.21<h1/>
复制代码
URL哈希配置

URL 哈希算法会根据请求的 URL 进行哈希计算,将请求分配到固定的后端服务器。这种算法同样可以实现会话保持,适用于基于 URL 的会话管理。
URL哈希配置使用hash指令来进行配置
10.0.0.10服务器中操作:
  1. [root@lb ~]# cat /etc/nginx/conf.d/lb_url.conf
  2. upstream lb_url {
  3.   server 10.0.0.20:1999;
  4.   server 10.0.0.21:1999;
  5. }
  6. server {
  7.   listen 6999;
  8.   server_name lb.huangSir-devops.com;
  9.   location / {
  10.     proxy_pass http://lb_url;
  11.     #转发客户端请求的域名
  12.     proxy_set_header Host $http_host;
  13.     #记录客户端请求的真实IP地址
  14.     proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  15.     proxy_set_header X-Real-Ip $remote_addr;
  16.   }
  17. }
  18. [root@lb ~]# nginx -t
  19. nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
  20. nginx: configuration file /etc/nginx/nginx.conf test is successful
  21. [root@lb ~]# nginx -s reload
复制代码
测试略
随机配置

随机算法会随机选择一个后端服务器来处理请求。这种算法简单且不考虑服务器的负载情况。
随机算法使用random来进行配置
10.0.0.10服务器中操作:
  1. [root@lb ~]# cat /etc/nginx/conf.d/lb_random.conf
  2. upstream lb_random {
  3.   random;
  4.   server 10.0.0.20:1999;
  5.   server 10.0.0.21:1999;
  6. }
  7. server {
  8.   listen 7999;
  9.   server_name lb.huangSir-devops.com;
  10.   location / {
  11.     proxy_pass http://lb_random;
  12.     #转发客户端请求的域名
  13.     proxy_set_header Host $http_host;
  14.     #记录客户端请求的真实IP地址
  15.     proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  16.     proxy_set_header X-Real-Ip $remote_addr;
  17.   }
  18. }
  19. [root@lb ~]# nginx -t
  20. nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
  21. nginx: configuration file /etc/nginx/nginx.conf test is successful
  22. [root@lb ~]# nginx -s reload
复制代码
使用curl命令进行测试,发现符合预期
  1. [root@lb ~]# curl 10.0.0.10:7999 -H huangSir-devops.com
  2. <h1>10.0.0.20<h1/>
  3. [root@lb ~]# curl 10.0.0.10:7999 -H huangSir-devops.com
  4. <h1>10.0.0.21<h1/>
  5. [root@lb ~]# curl 10.0.0.10:7999 -H huangSir-devops.com
  6. <h1>10.0.0.20<h1/>
  7. [root@lb ~]# curl 10.0.0.10:7999 -H huangSir-devops.com
  8. <h1>10.0.0.21<h1/>
  9. [root@lb ~]# curl 10.0.0.10:7999 -H huangSir-devops.com
  10. <h1>10.0.0.21<h1/>
复制代码
四层负载均衡实现

Nginx 实现四层负载均衡主要通过其 stream 模块完成。四层负载均衡工作在网络模型的第四层(传输层),基于 IP 地址和端口号进行流量分发,适用于 TCP 和 UDP 协议。
四层负载均衡主要通过报文中的目标地址和端口来分发流量。当 Nginx 接收到客户端的请求时,它会根据配置的负载均衡策略(如轮询、最少连接等),选择一个后端服务器,并将请求直接转发到该服务器。
相关配置

10.0.0.10服务其配置
  1. [root@lb ~]# cat /etc/nginx/nginx.conf
  2. user www-data;
  3. worker_processes auto;
  4. pid /run/nginx.pid;
  5. include /etc/nginx/modules-enabled/*.conf;
  6. events {
  7.         worker_connections 768;
  8.         # multi_accept on;
  9. }
  10. #配置四层负载均衡
  11. stream {
  12.   upstream backend{
  13.     server 10.0.0.20:8848;
  14.     server 10.0.0.21:8848;
  15.   }
  16.   server {
  17.     listen 9999;
  18.     #四层负载均衡没有http协议
  19.     proxy backend;
  20.     proxy_connect_timeout 1s;
  21.     proxy_timeout 3s;
  22.   }
  23. }
  24. http {
  25. #http相关内容
  26. }
复制代码
测试

10.0.0.20和10.0.0.21分别开启8848端口
  1. [root@master ~]# apt update -y
  2. [root@master ~]# apt install -y netcat
  3. [root@master ~]# nc -kl 8848
复制代码
10.0.0.10服务器使用telnet或者nc命令进行测试
  1. [root@lb ~]# echo 'test' | nc 10.0.0.10 9999
  2. [root@lb ~]# echo 'test' | nc 10.0.0.10 9999
  3. [root@lb ~]# echo 'test' | nc 10.0.0.10 9999
  4. [root@lb ~]# echo 'test' | nc 10.0.0.10 9999
复制代码
查看20服务器
  1. [root@master ~]# nc -kl 8848
  2. test
  3. test
  4. test
复制代码
查看21服务器
  1. [root@master ~]# nc -kl 8848
  2. test
  3. test
复制代码
nginx配置动静分离

在 Nginx 中实现动静分离是一种常见的优化策略,可以提高网站的响应速度并减轻应用服务器的负载。
动静分离是指将动态请求(如 PHP、JSP、ASP 等)和静态请求(如 HTML、CSS、JavaScript、图片等)分开处理。通过这种方式,可以将静态资源直接由 Nginx 提供,而动态请求则转发到后端应用服务器(如 Tomcat、PHP-FPM 等)
其主要实现方式就是用location的匹配规则将动态或者静态的请求转发到相对应的服务器上
配置实现方式

这里给几个案例,就不进行一一测试了
负载均衡案例
  1. #动态组
  2. upstream blog_pools {
  3. server 172.16.1.7:80;
  4. server 172.16.1.8:80;
  5. }
  6. #静态组
  7. upstream static_pools {
  8. server 172.16.1.9:80;
  9. }
  10. server {
  11. listen 80;
  12. server_name huangSir-devops.com;
  13. error_log /var/log/blog-error.log notice;
  14. access_log /var/log/blog-access.log main;
  15. #静态组的转发规则
  16. location ~* \.(jpg|jpeg|bmp|png|js|css|html)$ {
  17.   proxy_pass http://static_pools;
  18.   proxy_set_header Host $http_host;
  19.   proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  20.   proxy_set_header X_Real_Ip $remote_addr;
  21. }
  22. }
  23. #动态组的转发规则
  24. location / {
  25.   proxy_pass http://blog_pools;
  26.   proxy_set_header Host $http_host;
  27.   proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  28.   proxy_set_header X_Real_Ip $remote_addr;
  29. }
复制代码
单个nginx实现动静分离
  1. server {
  2.     listen 80;
  3.     server_name huangSir-devops.com;
  4.     # 静态资源请求
  5.     location ~* \.(jpg|jpeg|png|gif|css|js|ico|html)$ {
  6.         root /var/www/html/static;  # 静态资源目录
  7.         expires 30d;  # 设置缓存过期时间
  8.     }
  9.     # 动态请求转发到后端应用服务器
  10.     location / {
  11.         proxy_pass http://backend_server;  # 后端应用服务器地址
  12.         proxy_set_header Host $host;
  13.         proxy_set_header X-Real-IP $remote_addr;
  14.         proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  15.     }
  16. }
复制代码
来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
您需要登录后才可以回帖 登录 | 立即注册