1. 程式人生 > >NGINX + TOMCAT出現大量的TIME-WAIT狀態的TCP連線解決

NGINX + TOMCAT出現大量的TIME-WAIT狀態的TCP連線解決

記錄一次幫朋友排查應用變慢的問題,

訪問量變大的時候,請求響應變慢,但資料庫和伺服器相關資源都正在,我們看看一下連線數

netstat -n|awk '/^tcp/{++S[$NF]}END{for (key in S) print key,S[key]}'

意外的發現

[root@iZ25627ehy9Z hmkx]# netstat -n|awk '/^tcp/{++S[$NF]}END{for (key in S) print key,S[key]}'
TIME_WAIT 3114
CLOSE_WAIT 2
ESTABLISHED 250

TIME_WAIT狀態的連線竟然多大3000多,這時候懷疑這個造成的,所以就查了一下資料,主要原因:

1.nginx開啟了keepalive ,而且預設用的http1.1

2.tomcat開啟了keepalive,預設也使用http1.1

3.但是nginx代理卻使用的http1.0,預設不開啟keepalive,所以就造成了大量的TIME-WAID狀態的TCP連線

目前有兩個解決辦法

方法一:nginx官網提供

For HTTP, the proxy_http_version directive should be set to “1.1” and the “Connection” header field should be cleared:
參考地址:http://nginx.org/en/docs/http/ngx_http_upstream_module.html

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 "";
        ...
    }
}

方法二:從系統層面解決(不建議)

net.ipv4.tcp_syncookies = 1  
net.ipv4.tcp_tw_reuse = 1  
net.ipv4.tcp_tw_recycle = 1  
net.ipv4.tcp_fin_timeout = 30  
然後執行 /sbin/sysctl -p 讓剛新增的內容生效  
   
解釋下:  
net.ipv4.tcp_syncookies = 1 表示開啟SYN Cookies。當出現SYN等待佇列溢位時,啟用cookies來處理,可防範少量SYN攻擊,預設為0,表示關閉;  
net.ipv4.tcp_tw_reuse = 1 表示開啟重用。允許將TIME-WAIT sockets重新用於新的TCP連線,預設為0,表示關閉;  
net.ipv4.tcp_tw_recycle = 1 表示開啟TCP連線中TIME-WAIT sockets的快速回收,預設為0,表示關閉。  
net.ipv4.tcp_fin_timeout 修改系統預設的 TIMEOUT 時間  

理論上少量的TIME-WAIT佔用資源並不多,但不要忽略它,不然流量突然來臨會讓你措手不及,有待確認是否這個造成,目前未出現上次的