总是想起你 發表於 2023-8-21 00:00:00

预留端口避免占用ip_local_reserved_ports

<p><strong>问题描述:</strong><br>
业务遇到这个情况,在重启服务时,出现1986端口被占用而无法启动,非得等该端口释放后才启动成功。</p>
<p><strong>问题分析:</strong><br>
1986端口被该服务器上的客户端随机选取源端口给占用掉了。</p>
<p><strong>解决方案:</strong><br>
使用net.ipv4.ip_local_port_range参数,规划出一段端口段预留作为服务的端口,这种方法是可以解决当前问题,但是会有个问题,端口使用量减少了,当服务器需要消耗大量的端口号的话,比如反代服务器,就存在瓶颈了。<br>
最好的做法是将服务监听的端口以逗号分隔全部添加到ip_local_reserved_ports中,TCP/IP协议栈从ip_local_port_range中随机选取源端口时,会排除ip_local_reserved_ports中定义的端口,因此就不会出现端口被占用了服务无法启动。</p>
<p>ip_local_reserved_ports解释如下:<br>
ip_local_reserved_ports - list of comma separated ranges<br>
Specify the ports which are reserved for known third-party<br>
applications. These ports will not be used by automatic port<br>
assignments (e.g. when calling connect() or bind() with port<br>
number 0). Explicit port allocation behavior is unchanged.</p>
<p>The format used for both input and output is a comma separated<br>
list of ranges (e.g. "1,2-4,10-10" for ports 1, 2, 3, 4 and<br>
10). Writing to the file will clear all previously reserved<br>
ports and update the current list with the one given in the<br>
input.</p>
<p>Note that ip_local_port_range and ip_local_reserved_ports<br>
settings are independent and both are considered by the kernel<br>
when determining which ports are available for automatic port<br>
assignments.</p>
<p>You can reserve ports which are not in the current<br>
ip_local_port_range, e.g.:</p>
<p>$ cat /proc/sys/net/ipv4/ip_local_port_range<br>
32000 61000<br>
$ cat /proc/sys/net/ipv4/ip_local_reserved_ports<br>
8080,9148</p>
<p>although this is redundant. However such a setting is useful<br>
if later the port range is changed to a value that will<br>
include the reserved ports.</p>
<p>Default: Empty<br>
https://www.kernel.org/doc/Documentation/networking/ip-sysctl.txt</p><pre class="brush:bash;toolbar:false"># vim /etc/sysctl.conf
net.ipv4.ip_local_reserved_ports = 1986, 11211-11220
# sysctl -p</pre><p>注意:内核版本要大于2.6.18-164,否则不支持该参数。</p>
頁: [1]
查看完整版本: 预留端口避免占用ip_local_reserved_ports