页边剪报

摘记:Linux 下 TIME_WAIT、tw_reuse 与半连接队列指标核查

· 来源备忘:Vincent Bernat《Coping with the TCP TIME-WAIT state on busy Linux servers》 #linux#networking

在网上搜内核网络调优参数,十篇里有八篇还在抄早在 Linux 4.12 就被彻底移除的 net.ipv4.tcp_tw_recycle(NAT 环境下会导致丢包惨案)。把真正有用的几条诊断命令和结论摘出来留档。

Do not enable net.ipv4.tcp_tw_recycle! It was broken behind NAT and removed in Linux 4.12. On the client/outbound side, tcp_tw_reuse=1 (or default 2 for loopback in newer kernels) is safe when TCP timestamps are enabled.
— vincent.bernat.ch
# 按状态汇总当前 TCP 套接字数量(比 netstat 快得多)
ss -s

# 查监听队列溢出计数(重点看 ListenOverflows 和 ListenDrops)
nstat -az | grep -E 'TcpExtListen(Overflows|Drops)|TCPBacklogDrop'

# 看具体哪个监听端口的 Recv-Q 逼近了 Send-Q(即 backlog 上限)
ss -lnt

绝大多数时候服务端几千个 TIME_WAIT 根本不占多少内存,真正把客户端短连接打爆的往往是本地临时端口段 ip_local_port_range 不够用,或者反向代理到上游没开 HTTP keepalive 连接池。