温馨提示×

debian ulimit怎么配置

小樊
42
2026-09-09 23:16:09
栏目: 智能运维

在 Debian 里,ulimit 用来限制进程资源(打开文件数、进程数、内存等)。配置方式取决于你是临时生效还是永久生效,以及作用对象是当前 shell、某用户、某服务

下面按常见场景说明。


一、查看当前限制

ulimit -a

常用选项:

  • -n 打开文件数(file descriptors)
  • -u 最大进程数
  • -s 栈大小
  • -c core 文件大小

示例:

ulimit -n
ulimit -u

二、临时配置(当前 shell 生效)

仅在当前终端会话有效:

ulimit -n 65536
ulimit -u 4096

退出 shell 或重启后失效。


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

1. 使用 /etc/security/limits.conf

编辑:

sudo vi /etc/security/limits.conf

格式:

<用户/组>  <soft/hard>  <资源类型>  <值>

示例(用户 www):

www soft nofile 65536
www hard nofile 65536
www soft nproc 4096
www hard nproc 4096

通配符:

* soft nofile 65535
* 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 服务


四、Systemd 服务配置(非常重要)

如果你发现:

  • limits.conf 配了但 服务不生效
  • Nginx / MySQL / Java 服务报 too many open files

那是 systemd 不走 limits.conf

方法 1:服务级配置

编辑服务:

systemctl edit nginx

写入:

[Service]
LimitNOFILE=65536
LimitNPROC=4096

重载:

systemctl daemon-reload
systemctl restart nginx

方法 2:全局 systemd 限制

sudo vi /etc/systemd/system.conf
DefaultLimitNOFILE=65536
DefaultLimitNPROC=4096
systemctl daemon-reexec

五、系统级内核参数(可选)

有些资源还受内核限制:

cat /proc/sys/fs/file-max

临时:

sysctl -w fs.file-max=2097152

永久:

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

六、验证是否生效

对运行中的进程:

cat /proc/<pid>/limits

例如:

cat /proc/$(pgrep nginx | head -1)/limits

七、常见坑总结

limits.conf 对 systemd 服务无效
sudo ulimit 没意义(ulimit 是 shell 内建)
❌ 改完不重启 session / 服务
✅ 服务用 systemctl edit
✅ 用户用 limits.conf + pam


如果你能告诉我:

  • Debian 版本
  • 用户 还是 服务
  • 具体想改什么(如 nofile / nproc)

我可以给你精确配置示例

0