1、背景

研发反馈网站在使用过程中会偶发500报错。现有架构为Nginx反向代理到后端Java应用服务器。

2、解决过程

2.1、查看Nginx相关日志

发现在Nginx error log中出现socket() failed (24: Too many open files) while connecting to upstream报错

  1. 2019/07/25 08:31:31 [crit] 15929#15929: accept4() failed (24: Too many open files)
  2. 2019/07/25 08:31:31 [crit] 15930#15930: accept4() failed (24: Too many open files)
  3. 2019/07/25 08:31:31 [crit] 15930#15930: accept4() failed (24: Too many open files)

2.2、查看操作系统文件打开限制

首先第一反应就是系统打开文件描述符超过了限制,通过ulimit -a可以查看

]$ 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) 31140
max locked memory       (kbytes, -l) 64
max memory size         (kbytes, -m) unlimited
open files                      (-n) 4096
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) 31140
virtual memory          (kbytes, -v) unlimited
file locks                      (-x) unlimited

可以看到open files (-n) 4096,此数值就是系统允许的最大文件打开数,通过以下方式调整此数值。

修改系统中的 /etc/security/limits.conf文件中
]$ sudo vim /etc/security/limits.conf #在最后添加如下两行
* soft nofile 65535
* hard nofile 65535

修改后发现Nginx日志依旧报错Too many open files。

2.3、查看Nginx配置

这个系统参数修改后应该是立即生效的,既然Nginx依然报错,说明Nginx应用有默认配置。通过命令查看Nginx的配置

]$ grep 'open files' /proc/$( cat /var/run/nginx.pid )/limits
Max open files            1024                 4096                 files

发现Nginx的Max open files依旧没有变化。

2.4、修改Nginx配置

  • 修改启动脚本nginx.service ```bash

    修改配置文件

    ]$ vim /lib/systemd/system/nginx.service …… [Service] Type=forking LimitNOFILE=65535 # 添加此项 ……

重载服务

]$ systemctl daemon-reload


- 修改Nginx配置文件
```bash
]$ vim nginx.conf
# 添加以下内容
worker_rlimit_nofile 65535; 
events {
    worker_connections  65535;
}
# 重启 nginx:
]$ systemctl restart nginx
  • 再次查看配置和nginx日志文件,错误已经不在了。
    ]$ grep 'open files' /proc/$( cat /var/run/nginx.pid )/limits
    Max open files            65535                65535                files