Nginx反向代理与负载均衡终极指南

一、反向代理核心概念

1. 正向代理 vs 反向代理

类型 作用对象 用途 示例
正向代理 客户端 隐藏客户端身份 科学上网工具
反向代理 服务端 隐藏服务器架构 Nginx负载均衡

2. 反向代理核心优势

  • 安全性:隐藏后端服务器信息
  • 扩展性:轻松横向扩展服务
  • 灵活性:实现灰度发布、AB测试
  • 高可用:自动故障转移

二、基础反向代理配置

1. 最小化配置

location / {
    proxy_pass http://backend_server;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
}

2. 关键指令解析

指令 作用 示例值
proxy_pass 后端服务地址 http://10.0.0.1:8080
proxy_set_header 修改请求头 Host $host
proxy_redirect 重定向修正 default
proxy_next_upstream 故障转移条件 error timeout http_500

三、负载均衡策略详解

1. 轮询(Round Robin)

默认策略:均匀分配请求

upstream backend {
    server 10.0.0.1:8000;
    server 10.0.0.2:8000;
}

2. 加权轮询(Weighted Round Robin)

适用场景:服务器性能不均

upstream backend {
    server 10.0.0.1:8000 weight=3;  # 60%流量
    server 10.0.0.2:8000 weight=2;  # 40%流量
}

3. IP哈希(IP Hash)

特点:相同IP固定访问同一后端

upstream backend {
    ip_hash;
    server 10.0.0.1:8000;
    server 10.0.0.2:8000;
}

4. 最少连接(Least Connections)

适用场景:长连接服务

upstream backend {
    least_conn;
    server 10.0.0.1:8000;
    server 10.0.0.2:8000;
}

5. 响应时间优先(Fair)

需第三方模块:按响应时间动态分配

upstream backend {
    fair;
    server 10.0.0.1:8000;
    server 10.0.0.2:8000;
}

6. 哈希策略(Generic Hash)

自定义哈希键:如URL参数

upstream backend {
    hash $request_uri consistent;
    server 10.0.0.1:8000;
    server 10.0.0.2:8000;
}

四、故障转移与健康检查

1. 被动健康检查

upstream backend {
    server 10.0.0.1:8000 max_fails=3 fail_timeout=30s;
    server 10.0.0.2:8000 backup;  # 备用服务器
}
  • max_fails:允许失败次数
  • fail_timeout:失败后暂停时间
  • backup:标记为备用服务器

2. 主动健康检查(商业版)

health_check interval=5s uri=/health_check;

3. 故障转移条件

proxy_next_upstream error timeout http_502 http_503;

支持的条件:

  • error:连接错误
  • timeout:连接超时
  • http_500:后端返回500状态码
  • invalid_header:无效响应头

五、高级配置技巧

1. 长连接优化

upstream backend {
    server 10.0.0.1:8000;
    keepalive 32;  # 连接池大小
}

location / {
    proxy_http_version 1.1;
    proxy_set_header Connection "";
}

2. 缓冲区配置

proxy_buffering on;
proxy_buffer_size 4k;
proxy_buffers 8 16k;
proxy_busy_buffers_size 24k;

3. 超时控制

proxy_connect_timeout 5s;
proxy_send_timeout 10s;
proxy_read_timeout 30s;

六、完整配置示例

1. 电商站点负载均衡

upstream backend {
    least_conn;
    server api1.example.com:8000 weight=5;
    server api2.example.com:8000;
    server backup.example.com:8000 backup;
    keepalive 32;
}

server {
    listen 80;
    server_name shop.example.com;

    location / {
        proxy_pass http://backend;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

        # 故障转移规则
        proxy_next_upstream error timeout http_500 http_502 http_503;

        # 超时设置
        proxy_connect_timeout 3s;
        proxy_read_timeout 10s;
    }

    location /status {
        access_log off;
        allow 192.168.1.0/24;
        deny all;
        stub_status;
    }
}

2. 灰度发布配置

map $cookie_user_type $backend {
    default "production";
    "beta" "beta_backend";
}

upstream production {
    server 10.0.0.1:8000;
}

upstream beta_backend {
    server 10.0.0.2:9000;
}

server {
    location / {
        proxy_pass http://$backend;
    }
}

七、性能监控与调优

1. 监控指标

# 查看活跃连接
netstat -anp | grep nginx | grep ESTABLISHED | wc -l

# Nginx状态页
curl http://localhost/status

2. 关键性能参数

参数 建议值 说明
worker_processes CPU核数 auto自动检测
worker_connections 1024-4096 需结合系统限制
keepalive_requests 10000 单个连接最大请求数
keepalive_timeout 65s 长连接保持时间

八、常见问题解决方案

1. 502 Bad Gateway

  • 检查后端服务是否存活
  • 调整proxy_connect_timeout
  • 查看Nginx错误日志/var/log/nginx/error.log

2. 负载不均衡

  • 检查weight参数设置
  • 确认是否意外启用ip_hash
  • 使用least_conn策略优化长连接场景

3. Session保持问题

  • 使用ip_hashsticky模块
  • 改为共享Session存储(Redis)
  • 应用层实现无状态设计

通过合理配置反向代理和负载均衡策略,可以实现:
✅ 流量智能分配
✅ 自动故障转移
✅ 无缝水平扩展
✅ 业务连续性强保障

作者:admin  创建时间:2025-06-06 11:09
最后编辑:admin  更新时间:2025-06-07 09:49