Nginx tcp proxy module试用

本文介绍了如何使用Nginx的TCP代理模块进行TCP服务的代理,并通过创建日志目录和启动本地TCP程序进行实验。测试表明,该模块可以成功处理连接请求,且不影响HTTP代理。然而,当服务端关闭连接时,客户端可能无法立即感知,需要依赖Nginx的检查机制来关闭客户端连接。尽管存在这一小延迟,但不影响正常连接。作者对Nginx的工作原理进行了初步推测。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前文Nginx TCP Proxy模块的编译安装描述了如何编译tcp proxy module。现在来实验一下如何用。

首先要创建一个日志目录,因为t该模块的日志默认不在/var/log/nginx目录下

mkdir -p /etc/nginx/logs/

在nginx.conf文件中添加下面一节:

tcp {
    upstream tcpend {
    	     server localhost:7778;
	     check interval=3000 rise=2 fall=5 timeout=1000;
    }

    server {
    	   listen 7777;
       	   proxy_pass tcpend;
    }
}

注意,协议是tcp,不能将配置放在http下面。

然后启动本地的某个tcp程序,监听端口7778。用测试程序发起一个7777的连接请求,测试通过。而且不影响http的代理。

但是这个也有副作用,当服务端关闭连接的时候,客户端不可能立刻发觉连接已经被关闭,需要等到:

当Nginx在执行check规则时认为服务端链接关闭,Nginx会关闭与客户端的连接。

此时客户端才能察觉到连接关闭。好在不影响正常连接,所以不是大问题。

对于Nginx内部的工作原理,由于还没有研究过其实现代码,目前只能推测到此。


下面是check命令的解释:

check
    syntax: *check interval=milliseconds [fall=count] [rise=count]
    [timeout=milliseconds] [type=tcp|ssl_hello|smtp|mysql|pop3|imap]*

    default: *none, if parameters omitted, default parameters are
    interval=30000 fall=5 rise=2 timeout=1000*

    context: *upstream*

    description: Add the health check for the upstream servers. At present,
    the check method is a simple tcp connect.

    The parameters' meanings are:

    *   *interval*: the check request's interval time.

    *   *fall*(fall_count): After fall_count check failures, the server is
        marked down.

    *   *rise*(rise_count): After rise_count check success, the server is
        marked up.

    *   *timeout*: the check request's timeout.

    *   *type*: the check protocol type:

        1.  *tcp* is a simple tcp socket connect and peek one byte.

        2.  *ssl_hello* sends a client ssl hello packet and receives the
            server ssl hello packet.

        3.  *http* sends a http request packet, receives and parses the http
            response to diagnose if the upstream server is alive.

        4.  *smtp* sends a smtp request packet, receives and parses the smtp
            response to diagnose if the upstream server is alive. The
            response begins with '2' should be an OK response.

        5.  *mysql* connects to the mysql server, receives the greeting
            response to diagnose if the upstream server is alive.

        6.  *pop3* receives and parses the pop3 response to diagnose if the
            upstream server is alive. The response begins with '+' should be
            an OK response.

        7.  *imap* connects to the imap server, receives the greeting
            response to diagnose if the upstream server is alive.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值