golang 服務的文件超出系统限制(too many open files)

伍迪
Nov 4, 2020

内核的限制

整个操作系统可以打开的文件数受内核参数影响,可以通过以下命令查看

$ sysctl kern.maxfiles
$ sysctl kern.maxfilesperproc

在我电脑上输出如下

kern.maxfiles: 49152
kern.maxfilesperproc: 42576

好像已经很大了。

如果需要临时修改的话,运行如下命令

$ sudo sysctl -w kern.maxfiles=20480 # 或其他你选择的数字
$ sudo sysctl -w kern.maxfilesperproc=18000 # 或其他你选择的数字

永久修改,需要在 /etc/sysctl.conf 里加上类似的下述内容

kern.maxfiles=20480
kern.maxfilesperproc=18000

这个文件可能需要自行创建

launchd 对进程的限制

获取当前的限制:

$ launchctl limit maxfiles

输出类似这样:

maxfiles    256            unlimited

其中前一个是软限制,后一个是硬件限制。

临时修改:

$ sudo launchctl limit maxfiles 65536 200000

系统范围内修改则需要在文件夹 /Library/LaunchDaemons 下创建一个 plist 文件 limit.maxfiles.plist

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>limit.maxfiles</string>
<key>ProgramArguments</key>
<array>
<string>launchctl</string>
<string>limit</string>
<string>maxfiles</string>
<string>65536</string>
<string>200000</string>
</array>
<key>RunAtLoad</key>
<true/>
<key>ServiceIPC</key>
<false/>
</dict>
</plist>

修改文件权限

$ sudo chown root:wheel /Library/LaunchDaemons/limit.maxfiles.plist
$ sudo chmod 644 /Library/LaunchDaemons/limit.maxfiles.plist

载入新设定

$ sudo launchctl load -w /Library/LaunchDaemons/limit.maxfiles.plist

shell 的限制

通过下述命令查看现有限制

$ ulimit -a

得到如下输出

...
-n: file descriptors 256
...

通过 ulimit -S -n 4096 来修改。如果需要保持修改,可以将这一句命令加入你的 .bash_profile.zshrc 等。

总结

一般来说,修改了上述三个限制,重启一下,这个问题就可以解决了。

在实际操作中,我修改到第二步重启,第三个就自动修改了。

cannot assign requested address错误解决

`sysctl -w net.ipv4.tcp_fin_timeout=30 #修改系統默认的TIMEOUT时间,默认为60s
sysctl -w net.ipv4.tcp_timestamps=1 #修改tcp/ip协议配置, 通过配置/proc/sys/net/ipv4/tcp_tw_resue, 默认为0,修改为1,释放TIME_WAIT端口给新连接使用
sysctl -w net.ipv4.tcp_tw_recycle=1 #修改tcp/ip协议配置,快速回收socket资源,默认为0,修改为1:
sysctl -w net.ipv4.tcp_tw_reuse = 1 #允许端口重用
`

参考

[1] https://bbs.huaweicloud.com/blogs/108323
[2] https://www.launchd.info/
[3] https://en.wikipedia.org/wiki/Launchd#launchctl
[4] https://superuser.com/questions/433746/is-there-a-fix-for-the-too-many-open-files-in-system-error-on-os-x-10-7-1
[5] https://wilsonmar.github.io/maximum-limits/
[6] https://superuser.com/questions/302754/increase-the-maximum-number-of-open-file-descriptors-in-snow-leopard
[7] https://krypted.com/mac-os-x/maximum-files-in-mac-os-x/
[8] https://medium.com/mindful-technology/too-many-open-files-limit-ulimit-on-mac-os-x-add0f1bfddde

出處作者:macOS 解决 too many open files

--

--