温馨提示×

centos ulimit为何修改失败

小樊
57
2026-10-14 20:51:31
栏目: 智能运维

在 CentOS(以及大多数 Linux 发行版)中,ulimit 修改“失败”是非常常见的问题,通常不是命令本身的问题,而是作用范围、配置位置或系统限制导致的。下面按常见原因逐一说明。


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

ulimit -n 65535

✅ 只影响:

  • 当前 shell
  • 当前 shell 启动的子进程

❌ 不影响:

  • 已经运行的进程(如 sshd、nginx)
  • 其他终端 / 其他用户
  • 系统重启后

验证:

ulimit -n

如果在新终端里还是旧值,这是“正常现象”。


二、修改了 /etc/profile 但仍不生效

很多人会写:

echo "ulimit -n 65535" >> /etc/profile

但以下情况会失败:

1. 非登录 shell 不读 /etc/profile

  • cron
  • systemd 服务
  • 某些脚本

✅ 解决:

  • 登录 shell:用 source /etc/profile
  • 服务进程:不要依赖 ulimit

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

CentOS 7/8 使用 systemd,ulimit 对服务基本无效。

例如 nginx / mysql / java 服务:

systemctl start nginx

即使你设了:

ulimit -n 65535

nginx 实际仍是默认值(通常 1024)

✅ 正确做法(systemd)

编辑 service 文件:

vim /etc/systemd/system/nginx.service

或:

systemctl edit nginx

添加:

[Service]
LimitNOFILE=65535

然后:

systemctl daemon-reload
systemctl restart nginx

验证:

cat /proc/$(pidof nginx)/limits

四、/etc/security/limits.conf 没生效

正确写法示例:

* soft nofile 65535
* hard nofile 65535

但以下情况会“看起来失败”:

1. 只对“登录用户”生效

  • 不影响 systemd
  • 不影响 root 直接启动的进程(某些情况)

2. 使用了 PAM 限制

确认:

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

应有:

session required pam_limits.so

五、hard limit 比 soft limit 小(修改被拒绝)

ulimit -Hn   # 硬限制
ulimit -Sn   # 软限制

如果:

ulimit -Hn 1024
ulimit -n 65535   # 失败

❌ 不能超过 hard limit


六、内核参数限制(很少见但存在)

某些资源受内核限制:

sysctl fs.file-max

如果:

fs.file-max = 100000

你设 200000 的 nofile 也没意义。


七、Docker / 容器环境

在容器中:

  • ulimit 受宿主机限制
  • 需要在 docker run 时指定:
docker run --ulimit nofile=65535:65535

八、快速自查清单 ✅

# 当前 shell
ulimit -a

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

# systemd 服务
systemctl show <service> | grep Limit

# 配置文件
grep -R "nofile" /etc/security/limits.conf /etc/systemd

总结一句话

CentOS 上 ulimit“改了没用”,90% 是因为:
你改的是 shell,但进程是 systemd 启动的。

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

  • CentOS 版本(6 / 7 / 8 / Stream)
  • 改的是哪种资源(nofile / nproc / core)
  • 是登录用户还是某个服务

我可以直接给你对应可用的配置方案。

0 踩