DEBUG.WIKI
PanstarCloud:部署应用,接入 AI,云服务器与 AI 网关
晚安云;香港 CN2 ¥15/月
V.PS:让项目靠近用户,亚太、欧洲、北美 KVM VPS

解决 Nginx 报错 worker_rlimit_nofile is greater than sysctl fs.file-max

分析 Nginx 配置的 worker_rlimit_nofile 超过操作系统全局文件句柄上限警告的根因,提供 fs.file-max 内核调优与协同配置方案。

问题现象

在启动 Nginx 或测试配置文件时,控制台输出报警:

nginx: [warn] 12345#12345: the "worker_rlimit_nofile" directive (1048576) is greater than
the system-wide "fs.file-max" limit (65536), ignoring
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

Nginx 虽然能够启动,但实际生效的文件句柄上限被强制截断降级至 65536,无法应对极高并发请求。

触发根因

  1. 操作系统内核全局最大句柄数(fs.file-max)偏小:系统默认通常仅为 65536 或更低。
  2. Nginx 配置文件中设置的 worker_rlimit_nofile 超过了系统全局天花板:Nginx 无法向操作系统申请超过全局上限的资源配额。

诊断排查步骤

  1. 检查当前内核生效的全局文件句柄上限:
cat /proc/sys/fs/file-max

解决步骤与操作命令

步骤一:调大操作系统内核全局句柄上限

编辑 /etc/sysctl.conf:

sudo bash -c 'cat <<EOF >> /etc/sysctl.conf
fs.file-max = 2097152
fs.nr_open = 2097152
EOF'
sudo sysctl -p

将系统全局最大限制调高至 200 万。

步骤二:调大 Nginx 的 worker_rlimit_nofile 参数

编辑 /etc/nginx/nginx.conf 顶层主块:

user nginx;
worker_processes auto;
worker_rlimit_nofile 1048576; # 现在小于 fs.file-max

events {
    worker_connections 65535;
    use epoll;
}

步骤三:验证配置

重新执行配置校验:

sudo nginx -t

确认控制台输出不再出现任何 [warn] 警告。

步骤四:平滑热重载 Nginx 并验证进程生效限制

sudo nginx -s reload
cat /proc/$(pgrep -f "nginx: worker" | head -n 1)/limits | grep "Max open files"

确认工作进程的 Max open files 真实变更为 1048576。