前言:Nginx自1.9.0开始提供基于TCP/UDP的端口转发功能,但是直到最近版本才开始提供这种模式下的日志记录功能。关于Nginx的这个功能我之前写过一篇文章(https://www.zifangsky.cn/660.html),因此在这篇文章里我主要介绍下如何配置其日志记录功能
(1)下载:
1 | [root@app01 src]# wget http://nginx.org/download/nginx-1.12.2.tar.gz |
(2)编译安装:
1 2 3 4 | [root@app01 src]# tar -zxvf nginx-1.12.2.tar.gz [root@app01 src]# cd nginx-1.12.2 [root@app01 nginx-1.12.2]# ./configure --prefix=/usr/local/nginx --user=www --group=www --with-http_stub_status_module --with-pcre=/usr/local/src/pcre-8.38 --add-module=/usr/local/src/ngx_cache_purge-2.3 --with-http_gzip_static_module --with-stream [root@app01 nginx-1.12.2]# make && make install |
注:关于nginx的编译参数可以根据实际情况修改,但是“–with-stream”参数则是需要添加的
(3)修改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 26 27 28 29 30 31 | user www www; worker_processes 4; pid logs/nginx.pid; events { #use epoll; #Linux最常用支持大并发的事件触发机制 worker_connections 65535; } 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"'; access_log logs/access_8000.log proxy ; open_log_file_cache off; upstream zifangsky { #hash $remote_addr consistent; server 10.10.100.31:8000 weight=5 max_fails=1 fail_timeout=20s; } server { listen 8000; proxy_connect_timeout 10s; proxy_timeout 10s; proxy_pass zifangsky; tcp_nodelay on; } } |
在上面的配置文件中配置了在访问此服务器的8080端口时,会将流量相应转发到10.10.100.31这个服务器的8000端口上。另外,测试发现只有当一个会话结束之后nginx才会将相关日志记录到指定的日志文件中
注:其他的如:配置nginx的启动脚本、设置nginx开机自启动等操作就此省略了,如果需要可以自行参考我之前写的有关nginx的文章