在網(wǎng)上搜索 NGINX TIME_WAIT 大多數(shù)的解決方法是:
修改 /etc/sysctl.conf
文件
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_tw_recycle = 1
然后用命令啟用:
sudo /sbin/sysctl -p
然后看一下 TIME_WAIT 的數(shù)量:
netstat -n | awk '/^tcp/ {++S[$NF]} END {for(a in S) print a, S[a]}'
或
ss -ant | awk 'NR>1 {++s[$1]} END {for(k in s) print k,s[k]}'
就說行了.
然而,這個(gè)雞毛只是解決了 NGINX 服務(wù)器的 TIME_WAIT 問題, 對后端服務(wù)器一點(diǎn)幫助都沒有...
如上圖, 我就是按網(wǎng)上配置的, 后端服務(wù)器的 TIME_WAIT 還是多的不得了, 應(yīng)用程序報(bào)了大量的這個(gè)錯(cuò):
對端口的訪問被拒絕。
親測有效的方案是 keepalive
+ proxy_http_version 1.1
+ proxy_set_header Connection ""
upstream http_backend {
server 127.0.0.1:8080;
keepalive 16;
}
server {
...
location /http/ {
proxy_pass http://http_backend;
proxy_http_version 1.1;
proxy_set_header Connection "";
...
}
}
參考文檔
指令 keepalive xxx
的意思:
The connections parameter sets the maximum number of idle keepalive connections to upstream servers that are preserved in the cache of each worker process. When this number is exceeded, the least recently used connections are closed.
大至是說如果keepalive 的空閑連接數(shù)超過這個(gè)值, 就關(guān)掉最近最少使用的連接. 這個(gè) xxx 是數(shù)量的意思, 有人說這個(gè)是時(shí)間, 是不對的. 具體這個(gè)數(shù)值設(shè)為多少, 我沒有經(jīng)驗(yàn), 要慢慢調(diào)整吧.
keepalive
只有在 http1.1 下起作用, 所以要加上 proxy_http_version 1.1;
同時(shí)還要移除 http 請求頭中的 Connection 參數(shù), 因?yàn)樗赡茉O(shè)置成了 Close
proxy_set_header Connection ""
回頭看一下后端服務(wù)器的 TIME_WAIT