温馨提示×

ubuntu ulimit怎么修改

小樊
57
2026-10-17 07:07:33
栏目: 智能运维

在 Ubuntu 中修改 ulimit(用户资源限制)有多种方式,取决于你是临时生效还是永久生效,以及作用范围是当前 shell / 用户 / 系统。


一、查看当前 ulimit

ulimit -a

查看某一项,比如最大打开文件数:

ulimit -n

二、临时修改(仅当前 shell 会话)

ulimit -n 65535
ulimit -u 4096

常用参数:

  • -n:最大打开文件数(file descriptors)
  • -u:最大用户进程数
  • -s:栈大小
  • -c:core 文件大小

⚠️ 只对当前终端有效,重启或新开 shell 失效。


三、针对用户永久修改(推荐方式)

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

sudo vim /etc/security/limits.conf

示例(用户 ubuntu):

ubuntu soft nofile 65535
ubuntu hard nofile 65535
ubuntu soft nproc 4096
ubuntu hard nproc 4096

说明:

  • soft:软限制(可临时超过,但会被限制)
  • hard:硬限制(不能超过)
  • nofile:打开文件数
  • nproc:进程数

⚠️ 需要 重新登录 才生效。


2. 确保 PAM 启用 limits

检查:

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

应包含:

session required pam_limits.so

如果没有,可添加。


四、systemd 服务(重点!)

如果你修改了 limits.conf,但服务仍不生效,多半是因为使用了 systemd。

修改 systemd 服务限制

编辑服务:

sudo systemctl edit xxx.service

添加:

[Service]
LimitNOFILE=65535
LimitNPROC=4096

然后:

sudo systemctl daemon-reload
sudo systemctl restart xxx

查看是否生效:

cat /proc/<pid>/limits

五、全局临时修改(不推荐)

sudo prlimit --pid $$ --nofile=65535:65535

六、常见问题

1. root 用户不生效?

limits.conf 对 root 一般不限制,需显式写:

root soft nofile 65535
root hard nofile 65535

2. Docker 容器不生效?

需要在宿主机或 docker run 中加:

--ulimit nofile=65535:65535

如果你能告诉我:

  • Ubuntu 版本
  • 修改哪一项(如 nofile / nproc)
  • 是给普通用户、服务还是 Docker

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

0 踩