一直以来,Nginx 并不支持tcp协议,因此后台的一些基于TCP的业务就只能经过其余高可用负载软件来完成了,好比Haproxy。html
这算是一个nginx比较明显的缺憾。不过,在1.90发布后这个认知将获得改写:nginx
2015-04-28 | nginx-1.9.0 mainline version has been released, with the stream module for generic TCP proxying and load balancing.
nginx-1.9.0 已发布,该版本增长了 stream 模块用于通常的 TCP 代理和负载均衡。服务器 |
The ngx_stream_core_module module is available since version 1.9.0. This module is not built by default, it should be enabled with the --with-stream configuration parameter.网络
ngx_stream_core_module 这个模块在1.90版本后将被启用。可是并不会默认安装,须要在编译时经过指定 --with-stream 参数来激活这个模块。负载均衡
其余改进包括:运维
- Change: 删除过期的 aio 和 rtsig 事件处理方法
- Feature: 可在 upstream 块中使用 "zone" 指令
- Feature: 流模块,支持 TCP 代理和负载均衡
- Feature: ngx_http_memcached_module 支持字节范围
- Feature: Windows 版本支持使用共享内存,带随机化地址空间布局.
- Feature: "error_log" 指令可在 mail 和 server 级别
- Bugfix: the "proxy_protocol" parameter of the "listen" directive did not work if not specified in the first "listen" directive for a listen socket.
因此,咱们若是须要用到这个功能,就须要加上 --with-stream 参数从新编译nginx。对于已在线上运行的nginx,你可能要用到平滑升级来避免线上的服务被中断,能够参考张戈之前分享的教程:socket
最后贴一下官方分享的stream模块的简单配置demo:memcached
http://nginx.org/en/docs/stream/ngx_stream_core_module.html布局
worker_processes auto;
error_log /var/log/nginx/error.log info;
events {
worker_connections 1024;
}
stream {
upstream backend {
hash $remote_addr consistent;
server backend1.example.com:12345 weight=5;
server 127.0.0.1:12345 max_fails=3 fail_timeout=30s;
server unix:/tmp/backend3;
}
server {
listen 12345;
proxy_connect_timeout 1s;
proxy_timeout 3s;
proxy_pass backend;
}
server {
listen [::1]:12345;
proxy_pass unix:/tmp/stream.socket;
}
}
和http模块相似,简单明了。相信熟悉 nginx 的朋友很容易的就能完成一个 nginx 下的 TCP 负载均衡集群配置。
因为工做繁忙,实在是爱莫能助。还好最近公司给我招了个小鲜肉来作运维助理,等空下来了,我再去测一测这个 Nginx 的 TCP 代理和负载均衡功能。到时候再来博客分享一二,敬请期待!
下面测试nginx代理TCP协议的配置。
realserver : 10.134.241.68
nginx :10.134.72.166
客户端:10.129.157.168
TCP监听端口:2014
1、配置nginx
看官网上的文档 http://nginx.org/en/docs/stream/ngx_stream_core_module.html
nginx1.90对TCP协议的代理并非默认开启的,须要在编译的时候配置 --with-stream 参数:
[img]https://images0.cnblogs.com/blog2015/450613/201505/071746123452724.png[/img]
nginx.config文件参照官网:
stream {
upstream cloudsocket {
hash $remote_addr consistent;
server 10.134.241.68:2014 weight=5 max_fails=3 fail_timeout=30s;
}
server {
listen 2014;
proxy_connect_timeout 1s;
proxy_timeout 3s;
proxy_pass cloudsocket;
}
}
启动nginx,发现nginx已经开始监听2014端口了
2、测试客户端连realserver
在客户端经过telnet链接realserver的2014端口:
在realserver上查看网络链接:
能够正常链接
3、测试客户端链接nginx
在客户端经过telnet链接nginx所在服务器的2014端口
在nginx机器上查看网络链接
在realserver上查看网络链接
能够注意到nginx是给作了一个TCP链接的中转