一、Nginx代理服务器基础配置

1.1 HTTP代理配置

nginx
  http {
      upstream backend_servers {
          server backend1.example.com:8080;
          server backend2.example.com:8080;
          least_conn; # 负载均衡策略
      }

      server {
          listen 80;
          server_name example.com;

          location / {
              proxy_pass http://backend_servers;
              proxy_set_header Host $host;
              proxy_set_header X-Real-IP $remote_addr;
              proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            
              # 超时控制
              proxy_connect_timeout 30s;
              proxy_send_timeout 60s;
              proxy_read_timeout 60s;
          }
      }
  }

1.2 TCP/UDP流代理配置

nginx
  stream {
      upstream mysql_servers {
          server 192.168.1.100:3306;
          server 192.168.1.101:3306;
          least_conn;
      }

      server {
          listen 3306;
          proxy_pass mysql_servers;
          proxy_connect_timeout 5s;
          proxy_timeout 30s;
      }

      # UDP负载均衡示例
      upstream dns_servers {
          hash $remote_addr consistent;
          server 8.8.8.8:53;
          server 8.8.4.4:53;
      }

      server {
          listen 53 udp reuseport;
          proxy_pass dns_servers;
          proxy_timeout 20s;
      }
  }

二、Nginx性能优化实战

2.1 核心参数调优

nginx
  worker_processes auto;  # 自动检测CPU核心数
  worker_rlimit_nofile 102400;  # 最大文件描述符数

  events {
      use epoll;  # Linux最优IO模型
      worker_connections 10240;  # 单进程最大连接数
      multi_accept on;  # 启用多连接接受
  }

  http {
      # 连接超时控制
      keepalive_timeout 30s;
      send_timeout 3s;

      # 缓冲区优化
      client_body_buffer_size 128k;
      client_max_body_size 10m;

      # 压缩配置
      gzip on;
      gzip_min_length 1024;
      gzip_buffers 16 8k;
      gzip_comp_level 5;
      gzip_types text/plain application/json;
  }

2.2 高级优化技巧

  1. TCP优化
bash
  sysctl -w net.ipv4.tcp_fin_timeout=15
  sysctl -w net.ipv4.tcp_tw_reuse=1
  1. 文件描述符优化
bash
  echo "* soft nofile 65535" >> /etc/security/limits.conf
  echo "* hard nofile 65535" >> /etc/security/limits.conf

三、HTTP错误处理与自定义页面

3.1 常见错误代码解析

状态码类型典型场景
200成功正常请求响应
404客户端错误资源不存在
500服务器错误程序异常
502服务器错误网关代理失败
504服务器错误网关超时

3.2 自定义错误页面配置

nginx
  error_page 404 500 502 503 504 /custom_error.html;

  location = /custom_error.html {
      root /usr/share/nginx/html;
      internal;  # 禁止直接访问
  }

示例HTML页面

html
  <!DOCTYPE html>
  <html>
  <head>
      <title>服务器维护中</title>
      <style>
          body { background: #f0f0f0; text-align: center; padding: 50px; }
          .error-code { font-size: 72px; color: #333; }
          .message { font-size: 18px; color: #666; }
      </style>
  </head>
  <body>
      <div class="error-code">503</div>
      <p class="message">服务器正在维护,请稍后重试</p>
      <img src="data:image/png;base64,iVBORw0KGgo..." alt="维护中">
  </body>
  </html>

四、压力测试实战

4.1 工具选择对比

工具协议支持并发能力脚本扩展典型场景
ApacheBenchHTTP快速基准测试
wrkHTTPLua高并发性能测试
LocustHTTP超高Python复杂用户行为模拟

4.2 测试用例示例

使用wrk测试API性能

bash
  wrk -t8 -c200 -d30s -H "Authorization: Bearer xxx" \
      --script=post_request.lua \
      http://api.example.com/data

Lua脚本示例

lua
  wrk.method = "POST"
  wrk.body   = '{"key": "value"}'
  wrk.headers["Content-Type"] = "application/json"

4.3 测试结果分析

Running 30s test @ http://api.example.com/data
  8 threads and 200 connections
  Thread Stats   Avg      Stdev     Max   +/- Stdev
    Latency   152.44ms  38.67ms 521.23ms   85.67%
    Req/Sec    16.83k     2.10k   22.45k    78.23%
  503789 requests in 30.10s, 1.23GB read
Requests/sec:  16737.42
Transfer/sec:     41.32MB

五、综合调优策略

  1. 渐进式优化

    • 基准测试 → 调整参数 → 再次测试 → 分析瓶颈
    • 重点关注QPS、平均响应时间、错误率
  2. 监控体系搭建

    bash
      # Nginx状态页面
      location /nginx_status {
          stub_status on;
          access_log off;
          allow 127.0.0.1;
          deny all;
      }
    
      # 使用Prometheus+Grafana监控

  3. 安全增强

    • 限制连接速率:limit_conn_zone
    • 配置CC攻击防护:limit_req

通过本文的系统性配置与优化,可构建出高性能、高可用的Nginx代理服务器,结合科学的压力测试方法,能够确保服务在真实业务场景中的稳定性。实际调优过程中需根据具体业务特性持续迭代参数配置。

Logo

北京人形旗下天工造物具身智能开源社区,聚焦具身天工与慧思开物两大平台

更多推荐