要让nginx支持tcp/udp负载均衡,关键在于启用stream模块并配置顶层stream块:需用nginx -v验证--with-stream编译参数,stream与http同级,定义upstream和server,tcp默认、udp需显式声明udp,支持least_conn等算法及health_check探测,不支持ssl终止和七层路由。

要让 Nginx 支持 TCP/UDP 流量的负载均衡,关键在于启用并正确配置 stream 模块。它不依赖 HTTP 协议,而是直接在传输层工作,适合数据库、DNS、游戏服务器等场景。
确认 stream 模块已编译启用
执行命令验证:
nginx -V 2>&1 | grep with-stream
若输出含 with-stream,说明模块可用;若无输出,需重新编译 Nginx,添加 --with-stream 参数。注意使用 nginx -V(大写 V),不是 -v。
编写顶层 stream 块配置
stream 块与 http 块同级,不能嵌套在 http 内。基本结构如下:
- 定义 upstream 组,列出后端服务地址和端口
- 每个 server 块监听一个端口(TCP 默认,UDP 需加 udp 参数)
- 用 proxy_pass 指向 upstream 名或具体地址
示例(MySQL TCP 负载均衡):
stream {
upstream mysql_backend {
server 192.168.1.10:3306 max_fails=3 fail_timeout=30s;
server 192.168.1.11:3306 max_fails=3 fail_timeout=30s;
least_conn;
}
server {
listen 3306;
proxy_pass mysql_backend;
proxy_timeout 1h;
proxy_responses 1;
}
}
适配 UDP 与健康检查
UDP 无连接,不能靠 TCP 握手判断存活,需用 health_check + match 自定义探测逻辑:
- match 块定义发送内容(send)和期望响应(expect)
- health_check 设置探测间隔、成功/失败阈值,并引用 match 名
- server 监听时必须带 udp 参数
示例(DNS UDP 负载均衡):
stream {
match dns_response { expect ~* "\x81\x80"; }
upstream dns_udp {
server 192.168.2.5:53;
server 192.168.2.6:53;
health_check interval=5 passes=2 fails=3 match=dns_response;
}
server {
listen 53 udp;
proxy_pass dns_udp;
proxy_timeout 30s;
}
}
常用调优与注意事项
四层代理不处理应用层数据,但以下参数影响稳定性与性能:
- proxy_connect_timeout:建立上游连接的超时,默认 60s,建议设为 1–3s
- proxy_timeout:空闲连接保持时间,避免被防火墙或云 LB 中断
- least_conn:适合长连接、连接数不均的服务(如数据库)
- hash $remote_addr:实现客户端 IP 持久化调度(TCP 场景可用)
- 不支持 rewrite、header 修改、SSL 终止(除非用 stream_ssl_module)











