1. 程式人生 > >Nginx釋出1.9.0版本,新增支援TCP代理和負載均衡的stream模組

Nginx釋出1.9.0版本,新增支援TCP代理和負載均衡的stream模組


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

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

nginx1.90對TCP協議的代理並不是預設開啟的,需要在編譯的時候配置 --with-stream 引數:

[img]http://images.cnitblog.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連線的中轉。