温馨提示×

centos ulimit为什么失效

小樊
43
2026-09-30 05:43:20
栏目: 智能运维

在 CentOS(以及大多数 Linux 发行版)中,ulimit “失效”是一个非常常见的问题,通常不是 ulimit 本身坏了,而是作用范围、配置位置或系统限制导致了“看起来没生效”。

下面按最常见原因 → 排查方法 → 正确配置方式来说明。


一、最常见原因:ulimit 只对“当前 shell 及其子进程”生效

1️⃣ 你设置完 ulimit,但服务不是从这里启动的

ulimit -n 65535
./my_server

✅ 生效

但如果是:

systemctl start my_server

❌ 不生效

原因:

  • systemctl 启动的进程 不继承你 shell 的 ulimit
  • systemd 有自己的一套限制

✅ 正确方式(见后面 systemd 部分)


二、/etc/security/limits.conf 没生效的常见原因

2️⃣ limits.conf 只对「登录会话」生效

文件:

/etc/security/limits.conf

示例:

* soft nofile 65535
* hard nofile 65535

❌ 对以下情况不生效:

  • systemd 服务
  • 非登录 shell(cron、docker、某些守护进程)
  • 某些容器环境

✅ 生效条件:

  • 用户通过 login / ssh / su 登录
  • PAM 加载了 pam_limits.so

检查 PAM:

grep pam_limits /etc/pam.d/login
grep pam_limits /etc/pam.d/sshd

三、systemd 服务忽略 ulimit(CentOS 7+ 重点)

3️⃣ systemd 有独立的 Limit 配置

即使你设置了:

/etc/security/limits.conf

systemctl 启动的服务 完全不看它

✅ 必须改 service 文件:

/etc/systemd/system/xxx.service
[Service]
LimitNOFILE=65535
LimitNPROC=65535

然后:

systemctl daemon-reexec
systemctl restart xxx

查看是否生效:

cat /proc/<pid>/limits

四、用户类型不对(root 和普通用户)

4️⃣ * 不包含 root

* soft nofile 65535

❌ root 不生效

✅ 必须单独写:

root soft nofile 65535
root hard nofile 65535

五、内核参数比 ulimit 更“硬”

5️⃣ 系统级限制没调

即使 ulimit 设了,内核也可能拦你:

sysctl fs.file-max

如果太小:

fs.file-max = 1000000

生效:

sysctl -p

六、Docker / 容器环境

6️⃣ 容器内 ulimit 受宿主机限制

  • 容器里改 limits.conf 通常无效
  • 启动容器时要显式指定:
docker run --ulimit nofile=65535:65535 ...

七、快速排查 checklist ✅

你可以一步步确认:

# 当前 shell
ulimit -n

# 进程实际限制
cat /proc/<pid>/limits

# systemd 服务
systemctl show xxx | grep Limit

# 内核
sysctl fs.file-max

八、标准“正确姿势”总结

✅ 登录用户

/etc/security/limits.conf

✅ 系统服务(CentOS 7+)

/etc/systemd/system/xxx.service
LimitNOFILE=65535

✅ 内核

fs.file-max

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

  • CentOS 版本(6 / 7 / 8 / Stream)
  • 是 服务不生效 还是 命令行不生效
  • 具体是哪个限制(nofile / nproc / core / stack)

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

0 踩