温馨提示×

ubuntu ulimit错误怎么解

小樊
40
2026-10-26 04:12:52
栏目: 智能运维

在 Ubuntu 里遇到 ulimit 相关错误,通常不是“ulimit 命令本身坏了”,而是某个资源限制被触顶或配置没生效。下面按「常见错误 → 原因 → 解决办法」给你一个实战清单。


一、常见 ulimit 错误表现

  • bash: ulimit: open files: cannot modify limit: Operation not permitted
  • Too many open files
  • fork: retry: No child processes
  • ulimit: core file size: invalid argument
  • 服务启动时报 ulimit: error setting limit

二、先确认当前限制

ulimit -a

重点关注:

  • open files (-n)
  • max user processes (-u)
  • stack size (-s)

三、临时修改(仅当前 shell / 进程)

ulimit -n 65535
ulimit -u 4096

⚠️ 注意:

  • 只能调小或调到 hard limit 以内
  • 非 root 用户不能突破 hard limit

查看 hard limit:

ulimit -Hn

四、永久修改(推荐做法)

1️⃣ 修改 /etc/security/limits.conf

sudo vim /etc/security/limits.conf

示例(针对所有用户):

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

或指定用户:

www-data soft nofile 100000
www-data hard nofile 100000

⚠️ 生效条件:

  • 必须通过 PAM 登录(SSH / 桌面 / su -)
  • 对 systemd 服务不生效

2️⃣ systemd 服务(非常关键)

如果你是在 Docker / Nginx / MySQL / 自建服务 里报错:

方法 A:服务级配置

sudo systemctl edit nginx

写入:

[Service]
LimitNOFILE=65535
LimitNPROC=4096

然后:

sudo systemctl daemon-reload
sudo systemctl restart nginx

方法 B:全局 systemd

sudo vim /etc/systemd/system.conf
DefaultLimitNOFILE=65535
DefaultLimitNPROC=4096
sudo systemctl daemon-reexec

五、Docker 场景特别说明

Docker 容器默认继承宿主,但常被限制:

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

或在 docker-compose.yml:

ulimits:
  nofile:
    soft: 65535
    hard: 65535

六、常见坑总结

❌ limits.conf 改了但没用
✅ 多半是 systemd 服务没配

❌ sudo ulimit 报错
✅ ulimit 是 shell 内建命令,不能用 sudo 直接改其他进程

❌ 修改后重启 shell 没变化
✅ 确认是否用了 su 而不是 su -


七、快速自检清单

# 当前进程限制
cat /proc/$$/limits

# 某 PID
cat /proc/<pid>/limits

如果你愿意,可以把具体报错信息 + 使用场景(SSH / Docker / systemd / 某个程序)贴出来,我可以给你精确修改方案。

0 踩