前言
nginx從1.9.0開始,新增加了一個stream模組,用來實現四層協議的轉寄、代理或者負載平衡等。這完全就是搶HAproxy份額的節奏,鑒於nginx在7層負載平衡和web service上的成功,和nginx良好的架構,stream模組前景一片光明。 stream 模組編譯
stream模組預設沒有編譯到nginx, 編譯nginx時候 ./configure –with-stream 即可
官網:http://nginx.org/en/docs/stream/ngx_stream_core_module.html 用法
stream模組用法和http模組差不多,關鍵的是文法幾乎一致。熟悉http模組配置文法的上手更快
以下是一個配置了tcp負載平衡和udp(dns)負載平衡的例子, 有 server,upstream塊,而且還有server,
hash, listen, proxy_pass等指令,如果不看最外層的stream關鍵字,還以為是http模組呢。
worker_processes auto;error_log logs/error.stream.log info;events { worker_connections 1024;}stream { upstream backend { hash $remote_addr consistent; server 127.0.0.1:12346 weight=5; server 127.0.0.1:12347 max_fails=3 fail_timeout=30s; server 127.0.0.1:12348 max_fails=3 fail_timeout=30s; } upstream dns { server 17.61.29.79:53; server 17.61.29.80:53; server 17.61.29.81:53; server 17.61.29.82:53; } server { listen 12345; proxy_connect_timeout 1s; proxy_timeout 3s; proxy_pass backend; } server { listen 127.0.0.1:53 udp; proxy_responses 1; proxy_timeout 20s; proxy_pass dns; }}
stream core 一些變數
注意:變數支援是從 nginx 1.11.2版本開始的
$binary_remote_addr二進位格式的用戶端地址$bytes_received從用戶端接收到的位元組數$bytes_sent發往用戶端的位元組數$hostname串連網域名稱$msec毫秒精度的目前時間$nginx_versionnginx 版本$pidworker進程號$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_iso8601ISO 8601時間格式$time_local普通日誌格式的時間戳記
stream 模組
目前官網上列出的第三方模組、簡直就是http模組的鏡像、比如access模組存取控制ip和ip段,map模組實現映射、 geo模組實現地理位置映射、等等。使用這些模組的時候一定要看是哪個版本才支援的、比如log模組,只有在nginx-1.11.4才支援。
ngx_stream_core_modulengx_stream_access_modulengx_stream_geo_modulengx_stream_geoip_modulengx_stream_js_modulengx_stream_limit_conn_modulengx_stream_log_modulengx_stream_map_modulengx_stream_proxy_modulengx_stream_realip_modulengx_stream_return_modulengx_stream_split_clients_modulengx_stream_ssl_modulengx_stream_ssl_preread_modulengx_stream_upstream_modulengx_stream_upstream_hc_module