nginx 的 stream 模块一般以 stream { } 的形式存在于 nginx 配置文件中。如果执行 nginx -t 检查配置文件提示:nginx: [emerg] unknown directive "stream" 说明该版本不支持 stream 特性。
stream 模块是从 nginx 1.9.0 版本开始引入的,早期版本的 nginx 是不支持 stream 模块的。通过 nginx -v 检查版本号可以从基础上判断当前 nginx 版本是否能支持 stream 功能。除了 nginx 版本依赖之外,默认的编译选项也是没有开启 stream 功能的,可以通过 ngnix -V 检查构建 nginx 时是否启用了 stream 模块。
当然最简单的办法就是自己构建 nginx,在 configure 阶段加上 --with-stream 即可激活 stream 模块。
以下是构建过程:
wget https://nginx.org/download/nginx-1.27.1.tar.gz
$ tar zxvf nginx-1.27.1.tar.gz
cd nginx-1.24.1
configure --with-stream ./
make
make install
如果 configure 阶段提示 :
./configure: error: the HTTP rewrite module requires the PCRE library.
You can either disable the module by using --without-http_rewrite_module
option, or install the PCRE library into the system, or build the PCRE library
statically from the source with nginx by using --with-pcre=<path> option.
则禁用掉 HTTP 的 rewrite 模块,加上 --without-http_rewrite_module 选项:
./configure --with-stream --without-http_rewrite_module
编译完成后可以通过空的配置文件测试是否支持 stream 模块:
cat test.conf
events {}
stream {}
$PWD -T ./objs/nginx -c test.conf -p
如果不支持 stream 模块会提示:
$ ./objs/nginx -c test.conf -p $PWD -T
nginx: [emerg] unknown directive "stream" in /build/nginx-1.27.1/test.conf:2
nginx: configuration file /build/nginx-1.27.1/test.conf test failed
如果支持 stream 模块会提示:
./objs/nginx -c test.conf -p $PWD -T
nginx: the configuration file /build/nginx-1.27.1/test.conf syntax is ok
nginx: configuration file /build/nginx-1.27.1/test.conf test is successful
# configuration file /root/dist/nginx/nginx-1.27.1/test.conf:
events {}
stream {}
使用 stream 模块可以实现四层协议的转发、代理或负载均衡。比如将带 stream 功能的 nginx 服务器当作跳板机访问其它服务器的资源。
Demo 配置文件为:
user root;
worker_processes auto;
pid /run/nginx.pid;
events {
worker_connections 1024;
}
stream {
server {
listen 1521 so_keepalive=on;
proxy_pass 192.168.1.1:1521;
}
server {
listen 3389 so_keepalive=on;
proxy_pass 192.168.1.2:3389;
}
server {
listen 2222 so_keepalive=on;
proxy_pass 192.168.1.3:22;
}
}
访问 nginx 服务器的 1521、3389、2222 端口就相当于访问其它服务器的 Oracle 数据库、远程桌面、SSH 端口。
更多配置 demo 请参考:
注:
# Module ngx_stream_core_module
https://nginx.org/en/docs/stream/ngx_stream_core_module.html
原文始发于微信公众号(生有可恋):nginx stream 模块版本依赖
- 左青龙
- 微信扫一扫
-
- 右白虎
- 微信扫一扫
-
评论