nginx 配置4层代理

nginx-1.9.0 开始支持 TCP 代理,也就是4层代理,默认编译不会支持,需要加上 –with-stream 参数编译。

NGINX 编译

进入 nginx 目录

1
cd /home/fwj/nginx-1.15.9

编译

1
./configure --prefix=/usr/local/nginx --user=www --group=www --with-http_ssl_module --with-http_flv_module --with-http_stub_status_module --with-http_gzip_static_module --with-pcre --with-stream

配置 nginx.conf

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
user  www www;
worker_processes 1;


events {
worker_connections 1024;
}

stream{
log_format proxy '$remote_addr [$time_local] '
'$protocol $status $bytes_sent $bytes_received '
'$session_time "$upstream_addr" '
'"$upstream_bytes_sent" "$upstream_bytes_received" "$upstream_connect_time"';
open_log_file_cache off;
access_log logs/tcp-access.log proxy ;
upstream test{
server 127.0.0.1:666 weight=1 max_fails=1 fail_timeout=30s;
}
server{
listen 60;
proxy_pass test;
proxy_connect_timeout 8s;
proxy_timeout 7d;
}
}

执行

1
./nginx -c /usr/local/nginx/conf/nginx.conf

查看日志

1
2
3
4
# cat tcp-access.log
192.168.10.202 [06/Mar/2019:12:35:30 +0800] TCP 200 615 749 5.170 "127.0.0.1:666" "749" "615" "0.000"
192.168.10.202 [06/Mar/2019:12:36:07 +0800] TCP 200 246 419 5.008 "127.0.0.1:666" "419" "246" "0.000"
192.168.10.202 [06/Mar/2019:12:38:50 +0800] TCP 200 0 0 0.000 "127.0.0.1:666" "0" "0" "0.000"