【Nginx】负载平衡设置详解

[复制链接]
发表于 2025-9-19 20:11:50 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
Nginx作为高性能的HTTP服务器和反向署理服务器,提供了强大的负载平衡功能。本文将详细先容Nginx负载平衡的设置方法和相干战略。
一、根本负载平衡设置

1.单服务示例设置

设置nginx.conf模块
在Nginx设置文件中界说upstream模块:
  1. worker_processes auto;
  2. events {
  3.     worker_connections 1024;
  4. }
  5. http{
  6.         upstream backend {
  7.             server 192.168.1.101:8080;
  8.             server 192.168.1.102:8080;
  9.             server 192.168.1.103:8080;
  10.         }
  11.         server {
  12.             listen 80;
  13.             server_name example.com;
  14.             
  15.             location / {
  16.                 proxy_pass http://backend;
  17.                 proxy_set_header Host $host;
  18.                 proxy_set_header X-Real-IP $remote_addr;
  19.             }
  20.         }
  21. }
复制代码
2.多服务设置
  1. worker_processes auto;
  2. events {
  3.     worker_connections 1024;
  4. }
  5. http{
  6.     # 定义一个新的日志日志格式,包含 upstream_addr
  7.     log_format custom '$remote_addr - $remote_user [$time_local] "$request" '
  8.                       '$status $body_bytes_sent "$http_referer" '
  9.                       '"$http_user_agent" "$http_x_forwarded_for" '
  10.                       'upstream: $upstream_addr';
  11.     upstream server1{
  12.         server 192.168.211.5:9529;
  13.         server 192.168.211.169:9529;
  14.     }
  15.     upstream server2{
  16.         server 192.168.211.5:9528;
  17.         server 192.168.211.169:9528;
  18.     }
  19.     server {
  20.         listen       80;
  21.         server_name  localhost;
  22.         # 使用自定义的日志日志格式
  23.         access_log /opt/nginx/logs/access.log custom;
  24.         location ~ ^/server1/(.*)$ {
  25.             proxy_pass http://server1/$1;
  26.             proxy_set_header Host $host;
  27.             proxy_set_header X-Real-IP $remote_addr;
  28.             proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  29.             # proxy_set_header Content-Type application/json;
  30.         }
  31.         location ~ ^/server2/(.*)$ {
  32.             proxy_pass http://server2/$1;
  33.             proxy_set_header Host $host;
  34.             proxy_set_header X-Real-IP $remote_addr;
  35.             proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  36.         }
  37.         location ~* \.(css|js|html)$ {
  38.             root  /opt/nginx/html;    # 在本例中的绝对路径为 /usr/local/nginx/html
  39.         }
  40.         error_page 404 /404.html;
  41.         error_page 500 502 503 504 /50x.html;
  42.     }
  43. }
复制代码
3.docker启动nginx脚本

该脚本须要根据自己的docker镜像启动nginx的设置去修改
  1. #!/bin/bash
  2. # 定义变量
  3. CONTAINER_NAME="nlb-nginx"
  4. IMAGE_NAME="nginx:1.26"
  5. HOST_PORT="9090"  # 主机端口
  6. CONTAINER_PORT="80"  # 容器端口
  7. PORT_MAPPING="${HOST_PORT}:${CONTAINER_PORT}"
  8. NGINX_CONF_PATH="$(pwd)/nginx_server/nginx.conf"
  9. LOG_DIR="/var/server1/logs/proxy"
  10. TEST_URL="http://localhost:${HOST_PORT}"
  11. # 确保日志日志目录存在
  12. if [ ! -d "$LOG_DIR" ]; then
  13.     echo "Creating log directory: $LOG_DIR"
  14.     mkdir -p "$LOG_DIR" || {
  15.         echo "Failed to create log directory."
  16.         exit 1
  17.     }
  18. fi
  19. # 停止并删除旧容器(如果存在)
  20. echo "Stopping and removing existing container: $CONTAINER_NAME"
  21. docker stop "$CONTAINER_NAME" > /dev/null 2>&1
  22. docker rm -f "$CONTAINER_NAME" > /dev/null 2>&1
  23. # 启动新的 Nginx 容器
  24. echo "Starting new Nginx container: $CONTAINER_NAME"
  25. docker run -itd \
  26.   --name "$CONTAINER_NAME" \
  27.   -p "$PORT_MAPPING" \
  28.   -v "$NGINX_CONF_PATH:/opt/nginx/etc/nginx.conf" \
  29.   -v "$LOG_DIR:/opt/nginx/logs" \
  30.   "$IMAGE_NAME" \
  31.   /opt/nginx/sbin/nginx -c /opt/nginx/etc/nginx.conf -g "daemon off;" || {
  32.     echo "Failed to start container $CONTAINER_NAME."
  33.     exit 1
  34. }
  35. # 验证容器状态
  36. echo "Verifying container status..."
  37. if docker ps -f name="$CONTAINER_NAME" | grep -q "$CONTAINER_NAME"; then
  38.     echo "Container $CONTAINER_NAME is running successfully."
  39. else
  40.     echo "Container $CONTAINER_NAME failed to start."
  41.     exit 1
  42. fi
  43. # 测试访问
  44. echo "Testing access to $TEST_URL..."
  45. if curl -s -o /dev/null -w "%{http_code}" "$TEST_URL" | grep -q "200"; then
  46.     echo "Nginx is accessible at $TEST_URL"
  47. else
  48.     echo "Failed to access Nginx at $TEST_URL"
  49.     exit 1
  50. fi
  51. echo "Deployment completed successfully!"
复制代码
4.测试负载平衡-脚本

1.后端服务

示例:使用 Python Flask 实现
在每台后端服务器上运行以下简单的 Flask 应用步伐:
后端服务器 1 (192.168.211.5):
  1. from flask import Flask
  2. app = Flask(__name__)
  3. @app.route('/nginx_test')
  4. def server_info():
  5.     return "192.168.211.5"
  6. if __name__ == '__main__':
  7.     app.run(host='0.0.0.0', port=9529)
复制代码
后端服务器 2 (192.168.211.75):
  1. from flask import Flask
  2. app = Flask(__name__)
  3. @app.route('/nginx_test')
  4. def server_info():
  5.     return "192.168.211.75"
  6. if __name__ == '__main__':
  7.     app.run(host='0.0.0.0', port=9529)
复制代码
2.前端html测试
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4.     <meta charset="UTF-8">
  5.     <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6.     <title>Test Nginx Smartlabel</title>
  7. </head>
  8. <body>
  9.     <h1>Nginx and Flask Test Page</h1>
  10.     <p>Server Response: <strong id="server-response">Loading...</strong></p>
  11.     <script>
  12.         // JavaScript to send a GET request to the Flask endpoint
  13.         fetch('/server1/nginx_test', {
  14.             method: 'GET'
  15.         })
  16.         .then(response => response.json()) // Parse the JSON response
  17.         .then(data => {
  18.             document.getElementById('server-response').innerText = JSON.stringify(data);
  19.         })
  20.         .catch(error => {
  21.             document.getElementById('server-response').innerText = 'Error fetching data';
  22.         });
  23.     </script>
  24. </body>
  25. </html>
复制代码

  • 访问测试页面
    打开欣赏器并访问 http://localhost:9090/test.html。页面会表现雷同以下内容:
  1. Nginx and Flask Test Page
  2. Server Response: {"ip_info":"192.168.211.236","server":"server1"}
复制代码
二、负载平衡战略

Nginx支持多种负载平衡算法:

  • 轮询(默认)
  1. upstream backend {
  2.     server 192.168.1.101;
  3.     server 192.168.1.102;
  4. }
复制代码

  • 加权轮询
  1. upstream backend {
  2.     server 192.168.1.101 weight=3;
  3.     server 192.168.1.102 weight=1;
  4. }
复制代码

  • IP哈希(保持会话)
  1. upstream backend {
  2.     ip_hash;
  3.     server 192.168.1.101;
  4.     server 192.168.1.102;
  5. }
复制代码

  • 最少连接数
  1. upstream backend {
  2.     least_conn;
  3.     server 192.168.1.101;
  4.     server 192.168.1.102;
  5. }
复制代码

  • 基于相应时间(商业版)
  1. upstream backend {
  2.     fair;
  3.     server 192.168.1.101;
  4.     server 192.168.1.102;
  5. }
复制代码
三、高级设置选项


  • 服务器状态参数
  1. upstream backend {
  2.     server 192.168.1.101 max_fails=3 fail_timeout=30s;
  3.     server 192.168.1.102 backup;
  4.     server 192.168.1.103 down;
  5. }
复制代码

  • max_fails: 最大失败次数
  • fail_timeout: 失败超时时间
  • backup: 备用服务器
  • down: 标记服务器不可用
  • 康健查抄(商业版)
  1. upstream backend {
  2.     zone backend 64k;
  3.     server 192.168.1.101;
  4.     server 192.168.1.102;
  5.    
  6.     health_check interval=5s fails=3 passes=2 uri=/health;
  7. }
复制代码
四、TCP/UDP负载平衡

Nginx也可以用于TCP/UDP负载平衡:
  1. stream {
  2.     upstream tcp_backend {
  3.         server 192.168.1.101:3306;
  4.         server 192.168.1.102:3306;
  5.     }
  6.    
  7.     server {
  8.         listen 3306;
  9.         proxy_pass tcp_backend;
  10.     }
  11. }
复制代码
五、最佳实践


  • 会话保持:对于须要会话的应用,使用ip_hash或sticky模块
  • 康健查抄:设置公道的康健查抄参数
  • 日志记载:记载后端服务器的相应时间和状态
  • 超时设置:适当调解proxy连接超时时间
  • 缓冲区优化:根据应用特点调解缓冲区巨细
六、常见问题


  • 502错误:查抄后端服务器是否可用
  • 负载不均:调解权重或更换算法
  • 性能问题:优化worker_processes和worker_connections
七、总结

通过公道设置Nginx负载平衡,可以明显进步体系的可用性和性能。根据现实业务需求选择符合的负载平衡战略和参数设置是关键。
回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表