Linux设置预留端口,防止作为客户端随机端口使用ip_local_reserved_ports

问题

本周在生产上遇到一个问题, 应用会使用8014端口作为监听Listen状态,用于接受其他请求。但是服务在启动时,把8014作为客户端的临时端口去连数据库,导致在设置8014为监听端口时,由于端口被占用而失败。

 分析问题

1.设置ip_local_port_range参数,保留一段端口段预留作为服务的端口

使用net.ipv4.ip_local_port_range参数,规划出一段端口段预留作为服务的端口,这种方法是可以解决当前问题,但是会有个问题,端口使用量减少了,当服务器需要消耗大量的端口号的话,比如反代服务器,就存在瓶颈了。

2.设置ip_local_reserved_ports 参数,用逗号隔开,预留作为服务的端口

将服务监听的端口以逗号分隔全部添加到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 = 8014,60011-60014
# sysctl -p

参考资料:http://www.ttlsa.com/linux/reserved-port-to-avoid-occupying-ip_local_reserved_ports/

https://unix.stackexchange.com/questions/15511/how-do-i-reserve-ports-for-my-application

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值