too many open files
常见的报警问题,文件描述符被沾满,它是如何限制的? 我们又如何调整呢?
类Linux系统一切皆文件,我们监听端口使用的是文件,使用Redis建立的是tcp连接是文件等等,当系统中因为打开文件数过度,连接过度的时候就会发生以上问题
文件连接符限制
- 系统级:当前系统可打开的最大数量,通过 cat /proc/sys/fs/file-max 查看;
- 用户级:指定用户可打开的最大数量,通过 cat /etc/security/limits.conf 查看;
- 进程级:单个进程可打开的最大数量,通过 cat /proc/sys/fs/nr_open 查看;
使用ulimit -a 查看所有限制
root@ecs-99465:~# ulimit -a
core file size (blocks, -c) 0
data seg size (kbytes, -d) unlimited
scheduling priority (-e) 0
file size (blocks, -f) unlimited
pending signals (-i) 63907
max locked memory (kbytes, -l) 65536
max memory size (kbytes, -m) unlimited
open files (-n) 165535
pipe size (512 bytes, -p) 8
POSIX message queues (bytes, -q) 819200
real-time priority (-r) 0
stack size (kbytes, -s) 8192
cpu time (seconds, -t) unlimited
max user processes (-u) 63907
virtual memory (kbytes, -v) unlimited
file locks (-x) unlimited
临时修改
这种修改方式只对当前进程有效。若重新打开一个终端或是重启进程,这个参数都不会生效,所以不建议这样使用。
root@ecs-99465:~# ulimit -n
165535
root@ecs-99465:~# ulimit -n 165534
root@ecs-99465:~# ulimit -n
165534
查看默认设置
root@ecs-99465:~# cat /proc/sys/fs/file-max
1632068
root@ecs-99465:~# cat /proc/sys/fs/nr_open
1048576
root@ecs-99465:~# cat /etc/security/limits.conf | grep "nofile"
# - nofile - max number of open files
root soft nofile 165535
root hard nofile 165535
* soft nofile 165535
* hard nofile 165535
调整
直接编辑对应文件的限制数量即可
vim /proc/sys/fs/file-max
vim /proc/sys/fs/nr_open
vim /etc/security/limits.conf
注意事项
- 所有进程打开的文件描述符数不能超过/proc/sys/fs/file-max
- 单个进程打开的文件描述符数不能超过user limit中nofile的soft limit
- nofile的soft limit不能超过其hard limit
- nofile的hard limit不能超过/proc/sys/fs/nr_open
文件句柄查询命令
查看所有进程的文件打开数
root@ecs-99465:~# lsof | wc -l
5692
查看系统目前使用的文件句柄数
root@ecs-99465:~# cat /proc/sys/fs/file-nr
1440 0 1632068