一般nginx用於7層負載均衡和web service的代理轉發
nginx從1.9.0開始,新增加了一個stream模塊,用來實現四層協議的轉發、代理或者負載均衡等,類似阿里雲slb的 tcp協議模式
stream模塊默認沒有編譯到nginx, 編譯nginx時候帶上 --with-stream
1
|
. /configure --with-stream
|
如果nginx已經安裝,需要動態添加此模塊
1、獲取之前的編譯參數,進入nginx目錄
1
|
/app/nginx/sbin/nginx -V
|
得到結果:
--prefix=/app/nginx --with-http_ssl_module --with-http_stub_status_module --with-http_gzip_static_module --with-http_realip_module
2、在該服務器上新解壓一個相同版本的nginx安裝包,進行編譯
1
2
3
4
|
tar -xvf nginx-1.10.3. tar .gz
cd nginx-1.10.3
. /configure --prefix=/app/nginx --with-http_ssl_module --with-http_stub_status_module --with-http_gzip_static_module --with-http_realip_module --with-stream
make
|
3、替換編譯文件
1
2
|
cp /app/nginx/sbin/nginx /app/nginx/sbin/nginx .old
cp /app/nginx-1 .10.3 /opt/nginx /app/nginx/sbin
|
stream模塊的用戶和http類似與http同級
1
2
3
4
5
6
7
8
9
10
11
12
13
|
stream {
upstream back{
server 10.10.62.210:3306 up;
server 10.10.51.213:3306 up;
}
server {
listen 3301;
proxy_connect_timeout 5s;
proxy_timeout 300s;
proxy_pass back;
}
}
|
stream模塊中支持的變量
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
|
$binary_remote_addr
二進制格式的客戶端地址
$bytes_received
從客戶端接收到的字節數
$bytes_sent
發往客戶端的字節數
$ hostname
連接域名
$msec
毫秒精度的當前時間
$nginx_version
nginx 版本
$pid
worker進程號
$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_local
普通日誌格式的時間戳
|