nginx : TCP代理和負載均衡的stream模塊

一直以來,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

Nginx在線服務狀態下平滑升級或新增模塊的詳細操做記錄tcp

最後貼一下官方分享的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鏈接的中轉

相關文章
相關標籤/搜索