TIME_WAIT影響
大量的TIME_WAIT進程,會消耗系統大量資源,導致程序異常。
每一個tcp連接關閉后,主動關閉方會處於TIME_WAIT狀態,最長超時時間2MSL,在這期間端口資源不會被釋放。
RFC 793中規定MSL為2分鍾,實際由系統決定,通常在30-120s。
原理說明
一個連接的建立與斷開,正常過程至少需要來回7個包,分別是三次握手,四次揮手,才能完成。
Each socket in TIME_WAIT consumes some memory in the kernel, usually somewhat less than an ESTABLISHED socket yet still significant. A sufficiently large number could exhaust kernel memory, or at least degrade performance because that memory could be used for other purposes. TIME_WAIT sockets do not hold open file descriptors (assuming they have been closed properly), so you should not need to worry about a "too many open files" error.
TIME_WAIT中的每個套接字都會消耗內核中的一些內存,通常比已建立的套接字少一些,但仍然很大。足夠多的內存可能耗盡內核內存,或者至少降低性能,因為內存可以用於其他目的。TIME_WAIT套接字不包含打開的文件描述符(假設它們已經正確關閉),所以您不需要擔心“打開的文件過多”的錯誤。
The socket also ties up that particular src/dst IP address and port so it cannot be reused for the duration of the TIME_WAIT interval. (This is the intended purpose of the TIME_WAIT state.) Tying up the port is not usually an issue unless you need to reconnect a with the same port pair. Most often one side will use an ephemeral port, with only one side anchored to a well known port. However, a very large number of TIME_WAIT sockets can exhaust the ephemeral port space if you are repeatedly and frequently connecting between the same two IP addresses. Note this only affects this particular IP address pair, and will not affect establishment of connections with other hosts.
套接字綁定主機的 Src / Dst IP 地址和端口,因此在 TIME wait 間隔期間不能重復使用它。 (這是 TIME wait 狀態的目的。) 連接端口一般不是問題,除非您需要重新連接到相同的端口對。 大多數情況下,主機會使用臨時端口,連接固定的公有端口。 可是,如果頻繁的連接兩個相同的 IP 地址的臨時端口,會消耗大量的 TIME_wait 套接字的臨時端口空間。 請注意,這只影響這個特定的 IP 地址對,與其他主機建立連接的不受影響。
TCP 連接必須經過時間 2MSL 后才真正釋放掉占有資源Socket
(2MSL 時間的用意:為了保證 A 發送的最后一個 ACK 報文段能夠到達 B。
防止 “已失效的連接請求報文段”出現在本連接中.
A 在發送完最后一個 ACK 報文段后,需要經歷2MSL時間后,就可以本連接持續的時間內所產生的所有報文段,都從網絡中消失.這樣就可以使下一個新的連接中不會出現這種舊的連接請求報文段,從而保證了A發送的最后一個ACK報文順利的到達B。)
如果許多連接正在被快速打開和關閉,可能會引起大量的 TIME_WAIT 連接。
這會引發端口資源或其他資源的消耗,如果達到上限,那么就會引發創建新連接的障礙。
TIME_WAIT狀態的連接過多導致系統端口資源耗盡
大量的TIME_WAIT進程。簡單來說,每一個tcp連接關閉后,主動關閉方都會保留這個連接一段時間,這個時間內,這個連接的狀態是TIME_WAIT,端口資源不會被釋放。這個超時時間為2*MSL。RFC 793中規定MSL為2分鍾,實際由系統決定,通常在30-120s。這個網上有很多詳細解釋,這里不過多闡述。因為連接的關閉釋放有一定時間,並不是程序運行完就立刻釋放端口資源,所以當申請的連接進程較多的時候,端口資源就不夠用了。系統默認可用的端口資源:
$ cat /proc/sys/net/ipv4/ip_local_port_range
32768 61000
解決辦法:
1 擴大資源可用
1、 擴大端口范圍,linux是修改/etc/sysctl.conf
net.ipv4.ip_local_port_range = 1024 65535
2.#開啟重用。允許將TIME-WAIT sockets重新用於新的TCP連接,默認為0
net.ipv4.tcp_tw_reuse = 1
最后再執行sysctl -p
2. 優化自己的系統,減少短連接次數
因為tcp連接關閉后是有必要保留一段時間TIME_WAIT狀態的,我們的目標不應該是簡單的縮短TIME_WAIT時間,而是應該從根本上去優化我們的系統架構設計,減少不必要的短連接請求。
參考資料
引用:https://www.zybuluo.com/zhongdao/note/1466543
What is the cost of many TIME_WAIT on the server side? 在服務器端進行多次 TIME wait 的成本是多少?
https://stackoverflow.com/questions/1803566/what-is-the-cost-of-many-time-wait-on-the-server-side
(傳輸層)TCP協議
http://www.cnblogs.com/kzloser/articles/2582957.html
TIME_WAIT狀態的連接過多導致系統端口資源耗盡問題(2)
https://www.cnblogs.com/wangsili/p/3958371.html