问题描述: 业务遇到这个情况,在重启服务时,出现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端口的对外连接数。