解决 Nginx 出现 “socket() failed (24: Too many open files) while connecting to upstream”的办法

最近访问网站的时候出现 500 错误,日志中有一条:

socket() failed (24: Too many open files) while connecting to upstream

出现这个错误一般是因为系统设置的可打开文件描述符数量限制过小,导致 Nginx 进程在尝试打开更多文件时遇到了限制。

解决办法

1. 修改 limits.conf 文件

先使用命令 ulimit -a 查看 open files 的值,默认是 1024,有两种方法可以修改这个值。

ulimit -a 查看 open files 的值

方法一:使用命令 ulimit -n 20480 将最多可开启的文件数修改为 20480,这个数字根据实际情况自己定,但是此方法只对当前 shell 有效,退出后失效。

方法二:修改 /etc/security/limits.conf 文件,在最后加入以下内容:

* soft nofile 20480
* hard nofile 20480
root soft nofile 20480
root hard nofile 20480

*代表全局;soft 表示软件限制;hard 表示硬件限制;nproc 是最大进程数;nofile 是最大文件打开数,修改后需要重启系统才能生效。

2.修改 nginx.conf 文件

文件位于 /etc/nginx/nginx.conf

在 events{} 前加入一行:

worker_rlimit_nofile 20480;

该命令指定一个 Nginx 进程可以打开的最多文件描述符数目。这里将其设置为 20480,表示每个 Nginx 进程最多可以同时打开 20480 个文件。


以上两步操作,可以解决问题,还可以使用以下命令查看一下当前系统打开的文件句柄情况,帮助分析是否有其他进程占用了过多的文件描述符。左列是打开的文件数,右列是 PID。

lsof -n|awk '{print $2}'|sort|uniq -c|sort -nr|more

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>