温馨提示×

debian ulimit文件句柄怎调

小樊
37
2026-10-09 21:38:41
栏目: 智能运维

在 Debian 里“文件句柄(open files / 文件描述符)”限制通常分 3 层 来调,很多人只改了一层不生效,下面按 最常用、最稳妥 的方式说明。


一、先确认当前限制

ulimit -n

查看某个进程:

cat /proc/<pid>/limits | grep "Max open files"

二、临时调整(当前 shell / 进程)

ulimit -n 65535

⚠️ 只对当前 shell 和由其启动的进程有效,重启失效。


三、用户级永久配置(推荐)

1️⃣ 修改 /etc/security/limits.conf

sudo vim /etc/security/limits.conf

在末尾加(示例):

* soft nofile 65535
* hard nofile 65535

或指定用户:

www-data soft nofile 65535
www-data hard nofile 65535

2️⃣ 确保 PAM 生效

Debian 默认一般已开启,但确认一下:

grep pam_limits /etc/pam.d/common-session
grep pam_limits /etc/pam.d/common-session-noninteractive

应有:

session required pam_limits.so

⚠️ 需要重新登录或重启


四、systemd 服务(非常重要)

如果你是用 systemctl 启动的服务(Nginx / Redis / Java 等),limits.conf 不生效。

方法 1:服务级配置(推荐)

sudo systemctl edit nginx

写入:

[Service]
LimitNOFILE=65535

然后:

sudo systemctl daemon-reload
sudo systemctl restart nginx

方法 2:全局 systemd 限制

sudo vim /etc/systemd/system.conf
DefaultLimitNOFILE=65535
sudo systemctl daemon-reexec

五、系统级最大句柄数(内核)

查看:

cat /proc/sys/fs/file-max

临时:

sudo sysctl -w fs.file-max=2097152

永久:

sudo vim /etc/sysctl.conf
fs.file-max = 2097152
sudo sysctl -p

六、常见坑总结

✅ 改了不生效,90% 是:

  • systemd 服务没改 LimitNOFILE
  • 没重新登录 / 重启服务
  • Docker 容器没单独设

Docker 示例:

docker run --ulimit nofile=65535:65535 ...

七、快速检查清单

ulimit -n
cat /proc/sys/fs/file-max
systemctl show nginx | grep LimitNOFILE

如果你愿意,可以告诉我:

  • Debian 版本(11 / 12?)
  • 是 普通用户 / 服务 / Docker / K8s
  • 调不生效的具体现象

我可以直接给你 精确配置。

0 踩