0 前言
nginx从1.9.0开始,新增加了一个stream模块,用来实现四层协议的转发、代理或者负载均衡等。
1 备份原有配置
先到原nginx目录下备份nginx.conf 相关文件,如果是引用的外部配置文件,则忽略这一步
2 复制nginx正在使用的模块
进入nginx下sbin目录,执行 ./nginx -V 查看当前nginx安装信息,configure arguments后是当前nginx正在使用的模块,复制这个值
1 2 | cd /usr/local/nginx/sbin/ ./nginx -V |

3 执行./configure,追加 --with-stream
重新下载nginx安装包,放到local下,解压,进入到解压后的nginx-1.17.1目录
进入nginx-1.17.1根目录,检查安装环境是否有问题,有问题的话会报错。./configure命令后黏贴上面复制的内容,后面追加 --with-stream
1 | tar -zxvf nginx-1.17.1.tar.gz #解压nginx安装包 |
1 | cd /nginx-1.17.1 |
1 | ./configure --prefix=/home/deployer/soft/nginx_backward_proxy --with-stream --with-http_ssl_module |
常用configure命令设定安装参数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | # 常用模块配置 ./configure \ --prefix=/usr/local/nginx \ --pid-path=/var/run/nginx/nginx.pid \ --lock-path=/var/lock/nginx.lock \ --error-log-path=/var/log/nginx/error.log \ --http-log-path=/var/log/nginx/access.log \ --with-http_gzip_static_module \ --http-client-body-temp-path=/var/temp/nginx/client \ --http-proxy-temp-path=/var/temp/nginx/proxy \ --http-fastcgi-temp-path=/var/temp/nginx/fastcgi \ --http-uwsgi-temp-path=/var/temp/nginx/uwsgi \ --http-scgi-temp-path=/var/temp/nginx/scgi \ --with-stream \ --with-http_ssl_module |
4 编译make & make install,验证是否安装成功
1 2 | make #编译需要一两分钟的样子 make install #安装很快 |
重新查看nginx版本信息,可以看到stream模块已经安装成功

5 配置steam反向代理tcp
重新在nginx.conf文件上关联相关的配置文件,以及配置tcp socket sftp相关的配置,注意,stream和http同级,在最外层。
1 2 3 4 5 6 7 8 9 10 11 12 13 | stream { upstream sftp{ hash $remote_addr consistent; server 172.25.32.16:22; } server { listen 10022; proxy_connect_timeout 300s; proxy_timeout 300s; proxy_pass sftp; } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | worker_processes auto; error_log logs/error.stream.log info; events { worker_connections 1024; } stream { upstream backend { hash $remote_addr consistent; server 127.0.0.1:12346 weight=5; server 127.0.0.1:12347 max_fails=3 fail_timeout=30s; server 127.0.0.1:12348 max_fails=3 fail_timeout=30s; } upstream dns { server 17.61.29.79:53; server 17.61.29.80:53; server 17.61.29.81:53; server 17.61.29.82:53; } server { listen 12345; proxy_connect_timeout 1s; proxy_timeout 3s; proxy_pass backend; } server { listen 127.0.0.1:53 udp; proxy_responses 1; proxy_timeout 20s; proxy_pass dns; } } |
stream core 一些变量
注意:变量支持是从 nginx 1.11.2版本开始的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | $binary_remote_addr 二进制格式的客户端地址 $bytes_received 从客户端接收到的字节数 $bytes_sent 发往客户端的字节数 $hostname 连接域名 $msec 毫秒精度的当前时间 $nginx_version nginx 版本 $pid worker进程号 $protocol 通信协议(UDP or TCP) $remote_addr 客户端ip $remote_port 客户端端口 $server_addr 接受连接的服务器ip,计算此变量需要一次系统调用。所以避免系统调用,在listen指令里必须指定具体的服务器地址并且使用参数bind。 $server_port 接受连接的服务器端口 $session_time 毫秒精度的会话时间(版本1.11.4开始) $status 会话状态(版本1.11.4开始), 可以是一下几个值: 200 成功 400 不能正常解析客户端数据 403 禁止访问 500 服务器内部错误 502 网关错误,比如上游服务器无法连接 503 服务不可用,比如由于限制连接等措施导致 $time_iso8601 ISO 8601时间格式 $time_local 普通日志格式的时间戳 |