預留端口避免佔用ip_local_reserved_ports

問題描述: 業務遇到這個情況,在重啓服務時,出現1986端口被佔用而無法啓動,非得等該端口釋放後才啓動成功。

問題分析: 1986端口被該服務器上的客戶端隨機選取源端口給佔用掉了。

解決方案: 使用net.ipv4.ip_local_port_range參數,規劃出一段端口段預留作爲服務的端口,這種方法是可以解決當前問題,但是會有個問題,端口使用量減少了,當服務器需要消耗大量的端口號的話,比如反代服務器,就存在瓶頸了。 最好的做法是將服務監聽的端口以逗號分隔全部添加到ip_local_reserved_ports中,TCP/IP協議棧從ip_local_port_range中隨機選取源端口時,會排除ip_local_reserved_ports中定義的端口,因此就不會出現端口被佔用了服務無法啓動。

ip_local_reserved_ports解釋如下: ip_local_reserved_ports - list of comma separated ranges Specify the ports which are reserved for known third-party applications. These ports will not be used by automatic port assignments (e.g. when calling connect() or bind() with port number 0). Explicit port allocation behavior is unchanged.

The format used for both input and output is a comma separated list of ranges (e.g. "1,2-4,10-10" for ports 1, 2, 3, 4 and 10). Writing to the file will clear all previously reserved ports and update the current list with the one given in the input.

Note that ip_local_port_range and ip_local_reserved_ports settings are independent and both are considered by the kernel when determining which ports are available for automatic port assignments.

You can reserve ports which are not in the current ip_local_port_range, e.g.:

$ cat /proc/sys/net/ipv4/ip_local_port_range 32000 61000 $ cat /proc/sys/net/ipv4/ip_local_reserved_ports 8080,9148

although this is redundant. However such a setting is useful if later the port range is changed to a value that will include the reserved ports.

Default: Empty https://www.kernel.org/doc/Documentation/networking/ip-sysctl.txt

1
2
3

vim /etc/sysctl.conf

net.ipv4.ip_local_reserved_ports = 1986, 11211-11220

sysctl -p

[root@web01 ~]# cat /proc/sys/net/ipv4/ip_local_port_range
4000 65000

這個代表得是本地發起連接請求時可以獲取的隨機端口

#讓TIME_WAIT狀態可以重用,這樣即使TIME_WAIT佔滿了所有端口,也不會拒絕新的請求造成障礙 echo "1" > /proc/sys/net/ipv4/tcp_tw_reuse #讓TIME_WAIT儘快回收,我也不知是多久,觀察大概是一秒鐘 echo "1" > /proc/sys/net/ipv4/tcp_tw_recycle

很多文檔都會建議兩個參數都配置上,但是我發現只用修改tcp_tw_recycle就可以解決問題的了,TIME_WAIT重用TCP協議本身就是不建議打開的。

不能重用端口可能會造成系統的某些服務無法啓動,比如要重啓一個系統監控的軟件,它用了40000端口,而這個端口在軟件重啓過程中剛好被使用了,就可能會重啓失敗的。linux默認考慮到了這個問題,有這麼個設定:

#查看系統本地可用端口極限值 cat /proc/sys/net/ipv4/ip_local_port_range

用 這條命令會返回兩個數字,默認是:32768 61000,

說明這臺機器本地能向外連接61000-32768=28232個連接,注意是本地向外連接,不是這臺機器的所有連接,不會影響這臺機器的 80端口的對外連接數。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章