【Base】Nginx_服务器(Too_Many_Open_Files)

前言 & 背景


背景:

最近服务器把一个 socketIO 项目的 server 端,wss(https) 协议改到用 nginx 转发;随后查询 Nginx 的日志记录发现出现了很多错误日志:提示 Too many open files

猜测:

http请求结束后,打开的文件描述符会被自动关闭,所以程序中应当不存在没有关闭文件描述符的情况。猜测就是系统方面的问题了。

修复

确定系统核心允许文件打开的数量:

Ubuntu 上默认值一般远超过1024所以一般是不用修改的

1
$ sysctl -n -e fs.file-max

如果需要修改调整,可以编辑 /etc/sysctl.conf 这个文件

1
2
3
4
vim /etc/sysctl.conf 

# 加上 fs.file-max 的设置
fs.file-max = 100000

重新载入核心配置

1
sysctl -p

有关系统核心配置可以查看相应的man手册:man sysctl,man sysctl.conf

修改系统限制

修改 /etc/security/limits.conf 文件,设置打开的文件数量上限。(系统级别的)

1
2
* soft nofile 10240
* hard nofile 15360

其中第一行soft表示所有用户打开文件的数量限制为10240,如果超过这个数字则提示警告信息,但是依然可以打开文件。
第二行hard表示最大的打开文件数量不能超过15360,如果超过这个数字,则无法打开文件。
📢:根据实际情况,全局配置部分系统好像没有生效(具体原因还不清楚);要改成针对某个用户进行设置才能成功;如下:

1
2
3
4
5
nginx soft nofile 10240
nginx hard nofile 15360

root soft nofile 10240
root hard nofile 15360

更多详细的内容可以参考PAM的相关知识。
修改完这里之后,重新登录下机器查看 ulimit -n,就会发现设置生效了。

修改Nginx配置文件(程序级别)

1
2
3
4
# vim /etc/nginx/nginx.conf

# 添加配置
worker_rlimit_nofile 10240

该参数表示每个工作进程可以打开的文件数量。作用域和 worker_processes 一样。因为系统设定最大为 15360,由于每个工作进程分配不是均匀的,所以这里设置为10240
修改了nginx文件,需要reload一下。
至此,**nginx **中 Too many open files 的问题就算处理了,上面打开的文件数量数值设置可以根据服务器的情况进行调整

查看配置结果

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# 1. 通过PS 获取nginx的进程ID 
$ ps -ef | grep "nginx"
..
nginx 3166947 3055192  0 10:29 ?        00:01:11 nginx: worker process
..

# 2. 根据进程ID查看PROC文件获取进程信息
$ cat /proc/3166947/limits
Limit                     Soft Limit           Hard Limit           Units
Max cpu time              unlimited            unlimited            seconds
Max file size             unlimited            unlimited            bytes
Max data size             unlimited            unlimited            bytes
Max stack size            8388608              unlimited            bytes
Max core file size        0                    unlimited            bytes
Max resident set          unlimited            unlimited            bytes
Max processes             29395                29395                processes
Max open files            10240                10240                files
Max locked memory         65536                65536                bytes
Max address space         unlimited            unlimited            bytes
Max file locks            unlimited            unlimited            locks
Max pending signals       29395                29395                signals
Max msgqueue size         819200               819200               bytes
Max nice priority         0                    0
Max realtime priority     0                    0
Max realtime timeout      unlimited            unlimited            us

根据文件的展示可以得到 上限文件允许打开数量上升到了 10240 个;
改完这些之后,还需要修改下 nginx 打开的文件数量上限。

0%