温馨提示×

debian ulimit如何针对服务

小樊
37
2026-08-22 12:34:34
栏目: 智能运维

Debian 系统中,ulimit进程级 的限制;服务(service) 通常由 systemd 管理,因此不能简单地在 shell 里用 ulimit,而是要在 systemd service 配置PAM / 安全限制 中设置。

下面按 推荐方式 → 常见场景 说明。


一、Debian 服务(systemd)正确设置 ulimit ✅(最重要)

1️⃣ 查看当前服务限制

systemctl show your_service | grep -i limit

例如:

systemctl show nginx | grep Limit

2️⃣ 为某个服务单独设置 ulimit(推荐)

编辑服务:

systemctl edit your_service

例如:

systemctl edit nginx

写入:

[Service]
LimitNOFILE=65535
LimitNPROC=65535
LimitMEMLOCK=infinity

保存后:

systemctl daemon-reload
systemctl restart your_service

只对这一个服务生效


3️⃣ 常见 systemd ulimit 参数

参数 含义
LimitNOFILE 最大文件描述符
LimitNPROC 最大进程数
LimitSTACK 栈大小
LimitMEMLOCK 可锁定内存
LimitCORE core dump
LimitAS 地址空间

示例:

LimitNOFILE=100000
LimitNPROC=50000

二、全局 systemd 默认限制(不推荐)

编辑:

/etc/systemd/system.conf
DefaultLimitNOFILE=65535
DefaultLimitNPROC=65535

然后:

systemctl daemon-reexec

⚠️ 会影响所有服务


三、Debian 传统方式(非 systemd 服务)

1️⃣ /etc/security/limits.conf

⚠️ 只对登录用户生效,对 systemd 服务无效

/etc/security/limits.conf

示例:

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

⚠️ 注意:

  • root 不生效(需单独写)
  • 对 systemd service 不生效

2️⃣ PAM 启用(仅限登录)

确保:

/etc/pam.d/common-session

包含:

session required pam_limits.so

四、容器内服务(Docker / LXC)

Docker

docker run --ulimit nofile=65535:65535 nginx

docker-compose

ulimits:
  nofile:
    soft: 65535
    hard: 65535

五、验证是否生效 ✅

查看运行中的服务限制

cat /proc/$(pidof your_service)/limits

或:

systemctl status your_service

六、常见错误 ❌

错误 原因
ulimit -n 65535 没用 只对当前 shell
limits.conf 对 nginx 无效 nginx 是 systemd 服务
systemctl restart 后没变化 忘记 daemon-reload
root 不生效 limits.conf 默认不限制 root

七、总结(推荐做法)

Debian + systemd 服务

systemctl edit your_service
[Service]
LimitNOFILE=65535

临时测试

prlimit --pid <PID> --nofile=65535

容器

docker run --ulimit

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

  • 哪个服务(nginx / mysql / java / docker)
  • Debian 版本
  • 想限制 哪一项(fd / 进程 / 内存)

我可以给你 精确配置示例

0