預留端口避免占用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

# 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端口的對外連接數。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM