nginx stream模块需显式启用且与http同级:未编译则报“unknown directive 'stream'”,须用nginx -v检查--with-stream;ubuntu装nginx-full,centos装nginx-mod-stream;配置必须置于events后、http外,proxy_pass仅支持ip:port或upstream名,不支持http协议前缀。

Nginx 的 Stream 模块专为四层(TCP/UDP)流量设计,不解析应用层协议,只做透明转发。它适合数据库、Redis、Kafka、游戏服务器等非 HTTP 场景,但配置有明确约束,稍不注意就会启动失败或转发异常。
Stream 模块必须启用且位置正确
Nginx 默认不带 Stream 功能。启动时报 unknown directive "stream",说明模块未编译进二进制。
- 运行
nginx -V 2>&1 | grep with-stream,无输出即未启用 - Ubuntu/Debian:安装
nginx-full(不是nginx-light或nginx-core) - CentOS/RHEL 8+:需额外安装
nginx-mod-stream并确认模块已加载(检查/usr/lib64/nginx/modules/下是否有ngx_stream_module.so) - 源码编译:
./configure --with-stream --with-stream_ssl_module
配置结构必须顶层平级,不能嵌套
Stream 块和 http 块是同级的 main context 配置,绝不能写在 http 内部。
- ✅ 正确结构:
events { ... } stream { upstream ... server { ... } } http { ... } - ❌ 错误写法:把
stream { }缩进到http { }里,nginx -t直接报错 - 若用
include拆分配置,确保include /etc/nginx/stream/*.conf;这行写在stream { }块内部,而非 http 块中
proxy_pass 只认 IP:PORT 或 upstream 名,不支持协议前缀
Stream 是纯四层转发,不处理 URL 或 HTTP 头。
- ✅ 正确:
proxy_pass 10.0.1.5:3306;或proxy_pass backend_redis; - ❌ 错误:
proxy_pass http://10.0.1.5:3306;→ 启动失败,提示 “invalid port in upstream” - 若后端用域名(如
db.example.com),必须配resolver,否则 DNS 解析失败导致连接超时resolver 8.8.8.8 valid=30s; upstream backend { server db.example.com:6379; }
健康检查与负载策略要按场景选型
Stream 模块原生不支持 HTTP 探针,仅能基于 TCP 连通性判断。
- 开源版 Nginx:依赖
proxy_next_upstream on+ 超时参数实现被动容错proxy_next_upstream on; proxy_connect_timeout 3s; proxy_timeout 30s;
- 如需主动健康检查,需编译
--with-stream_upstream_check_module,启用tcp_checkupstream redis_pool { server 192.168.1.10:6379; check interval=3 rise=2 fall=3 timeout=1 type=tcp; } - 负载算法支持
least_conn、hash $remote_addr(会话保持)、ip_hash(注意 IPv6 兼容性),不支持weight在所有版本中都生效,需确认 Nginx 版本 ≥ 1.9.1
不复杂但容易忽略











