一直以來,Nginx 並不支持tcp協議,所以后台的一些基於TCP的業務就只能通過其他高可用負載軟件來完成了,比如Haproxy。
這算是一個nginx比較明顯的缺憾。不過,在1.90發布后這個認知將得到改寫:
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,你可能要用到平滑升級來避免線上的服務被中斷,可以參考張戈以前分享的教程:
最后貼一下官方分享的stream模塊的簡單配置demo:
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
一、配置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端口了
二、測試客戶端連realserver
在客戶端通過telnet連接realserver的2014端口:
在realserver上查看網絡連接:
可以正常連接
三、測試客戶端連接nginx
在客戶端通過telnet連接nginx所在服務器的2014端口
在nginx機器上查看網絡連接
在realserver上查看網絡連接
可以注意到nginx是給做了一個TCP連接的中轉