一般nginx用于7层负载均衡和web service的代理转发
nginx从1.9.0开始,新增加了一个stream模块,用来实现四层协议的转发、代理或者负载均衡等,类似阿里云slb的 tcp协议模式
stream模块默认没有编译到nginx, 编译nginx时候带上 --with-stream
1 | . /configure --with-stream |
如果nginx已经安装,需要动态添加此模块
1、获取之前的编译参数,进入nginx目录
1 | /app/nginx/sbin/nginx -V |
得到结果:
--prefix=/app/nginx --with-http_ssl_module --with-http_stub_status_module --with-http_gzip_static_module --with-http_realip_module
2、在该服务器上新解压一个相同版本的nginx安装包,进行编译
1 2 3 4 | tar -xvf nginx-1.10.3. tar .gz cd nginx-1.10.3 . /configure --prefix=/app/nginx --with-http_ssl_module --with-http_stub_status_module --with-http_gzip_static_module --with-http_realip_module --with-stream make |
3、替换编译文件
1 2 | cp /app/nginx/sbin/nginx /app/nginx/sbin/nginx .old cp /app/nginx-1 .10.3 /opt/nginx /app/nginx/sbin |
stream模块的用户和http类似与http同级
1 2 3 4 5 6 7 8 9 10 11 12 13 | stream { upstream back{ server 10.10.62.210:3306 up; server 10.10.51.213:3306 up; } server { listen 3301; proxy_connect_timeout 5s; proxy_timeout 300s; proxy_pass back; } } |
stream模块中支持的变量
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 | $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_local 普通日志格式的时间戳 |