Linux内核TCP连接Keep-Alive timeout的配置
source link: https://zhangrr.github.io/posts/20211102-tcp_keealive/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Linux内核TCP连接Keep-Alive Timeout的配置
Custom Configuration of TCP Socket Keep-Alive Timeouts
这是个古老的话题,我们在机器的优化中,需要设置 TCP Socket 的 Timeout 参数
用来加快 TCP 关闭无用闲置连接的时间
Linux 内核中有三个缺省参数:
-
tcp_keepalive_time
plaintext- 缺省是 7200 秒
-
tcp_keepalive_probes
plaintext -
tcp_keepalive_intvl
plaintext- 缺省是 75 秒
处理流程如下:
一、客户端打开一个 TCP socket 连接,开始跟服务器通讯
二、如果这条 socket 连接空闲没有任何数据传输,静默了 tcp_keepalive_time
秒后,那么客户端会主动发送一个空的 ACK
包到服务器
三、那么,根据服务器是否回应了一个相应的 ACK 包来判断
ACK
- 未回应
- 等待
tcp_keepalive_intvl
秒,然后再发一个ACK
包 - 重复以上等待并发送 ACK 包的过程,直到次数等于
tcp_keepalive_probes
- 如果第2步做完还收不到任何回应,发送一个
RST
包并关闭连接
- 等待
- 回应了: 回到上述第二步
那么缺省情况下,7200+75×9,一个没有任何数据传输的 socket 才会被关闭,大概是2小时11分钟。
这个时间太长了。需要优化一下:
net.ipv4.tcp_keepalive_time = 300
net.ipv4.tcp_keepalive_probes = 5
net.ipv4.tcp_keepalive_intvl = 15
上面的时间是 300 + 5x15,大概是6分钟,大大缩短释放空闲 socket 的时间
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK