温馨提示×

Debian ulimit限制如何解除

小樊
46
2026-07-23 21:19:01
栏目: 智能运维

在 Debian(以及大多数 Linux 发行版)中,ulimit 限制来自 PAM、systemd、Shell 启动脚本 等多个层面。要“解除”或“提高”限制,需要分层处理,否则你改了也没用。

下面按最常见场景给你一个完整、实用的做法。


一、ulimit 是什么

ulimit 控制的是 当前 shell 及其子进程 的资源限制:

ulimit -a

常见限制:

  • 最大打开文件数(open files)
  • 最大进程数(max user processes)
  • core dump 大小
  • 栈大小等

⚠️ ulimit 不是全局系统限制,而是“进程级”限制


二、临时解除(仅当前 shell,重启失效)

1️⃣ 临时提高限制

ulimit -n 65535        # 打开文件数
ulimit -u 65535        # 最大进程数

⚠️ 注意:

  • 普通用户 不能调高超过系统硬限制
  • 只能降低或调到硬限制以内

查看硬限制:

ulimit -Hn
ulimit -Hu

三、永久解除(推荐做法)

✅ 方法一:修改 /etc/security/limits.conf(传统方式)

编辑:

sudo nano /etc/security/limits.conf

在末尾添加(示例):

* soft nofile 65535
* hard nofile 65535
* soft nproc 65535
* hard nproc 65535

说明:

  • * 表示所有用户(可换成用户名)
  • soft:当前生效
  • hard:上限
  • nofile:打开文件数
  • nproc:进程数

⚠️ 注意
这种方式 只在以下情况生效

  • 通过 login shell
  • 并且 PAM 启用了 limits

✅ 方法二:确保 PAM 启用 limits(非常重要)

检查:

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

如果没有,添加:

session required pam_limits.so

(Debian 默认一般已启用)


四、systemd 系统(Debian 8+ 必须看)

如果你发现:

  • ulimit -n 是 1024
  • limits.conf 改了也没用

很可能被 systemd 覆盖

1️⃣ 查看 systemd 限制

systemctl show --property=DefaultLimitNOFILE

2️⃣ 修改 systemd 全局限制

编辑:

sudo nano /etc/systemd/system.conf

添加或修改:

DefaultLimitNOFILE=65535
DefaultLimitNPROC=65535

然后:

sudo systemctl daemon-reexec

(或重启)


五、针对某个 systemd 服务解除限制

如果是某个服务(如 nginx、mysql、docker):

sudo systemctl edit servicename

写入:

[Service]
LimitNOFILE=65535
LimitNPROC=65535

然后:

sudo systemctl restart servicename

六、Docker / 容器环境特别注意

Docker 默认继承宿主机限制,但会被 systemd / Docker 本身限制。

临时解除(运行容器时):

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

Docker daemon 限制(Debian systemd):

sudo nano /etc/systemd/system/docker.service.d/override.conf
[Service]
LimitNOFILE=65535
LimitNPROC=65535
sudo systemctl daemon-reload
sudo systemctl restart docker

七、验证是否生效

ulimit -n
ulimit -u
cat /proc/$(pidof your_process)/limits

八、常见坑总结(非常重要)

问题 原因
limits.conf 没用 systemd 覆盖
普通用户调不高 超过 hard limit
SSH 登录不生效 PAM 未启用
Docker 不生效 daemon 限制
只改 shell 没用 服务不是 shell 启动

九、如果你愿意,我可以帮你精准定位

你可以直接告诉我:

  1. Debian 版本(cat /etc/debian_version
  2. 普通用户 / root / 服务 / Docker
  3. 具体想解除哪种限制(文件数 / 进程数 / 其它)

我可以给你 一条最精简、一定生效的方案

0