温馨提示×

怎样修改debian ulimit

小樊
42
2026-09-19 02:56:16
栏目: 智能运维

在 Debian 中修改 ulimit(资源限制)有多种方式,取决于你是想临时生效针对某个用户/服务生效,还是系统级永久生效。下面按常见场景说明。


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

直接在终端执行:

ulimit -n 65535      # 打开文件数
ulimit -u 4096       # 最大进程数
ulimit -s 8192       # 栈大小(KB)

查看当前限制:

ulimit -a

⚠️ 只对当前 shell 及其子进程有效,重启或新开终端失效。


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

方法 1:修改 /etc/security/limits.conf

编辑文件:

sudo nano /etc/security/limits.conf

示例(用户 www):

www soft nofile 65535
www hard nofile 65535
www soft nproc 4096
www hard nproc 4096

说明:

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

⚠️ 需要 PAM 支持,确保以下文件存在且未被注释:

/etc/pam.d/common-session
/etc/pam.d/common-session-noninteractive

应包含:

session required pam_limits.so

重新登录后生效。


三、systemd 服务修改(非常重要)

如果你是用 systemctl 启动的服务(如 nginx、mysql、redis),limits.conf 不会生效

方法 1:服务级配置

sudo systemctl edit nginx

添加:

[Service]
LimitNOFILE=65535
LimitNPROC=4096

然后:

sudo systemctl daemon-reload
sudo systemctl restart nginx

查看:

cat /proc/$(pgrep nginx | head -1)/limits

方法 2:全局 systemd 默认限制

sudo nano /etc/systemd/system.conf

修改:

DefaultLimitNOFILE=65535
DefaultLimitNPROC=4096
sudo systemctl daemon-reexec

四、系统级内核参数(可选)

某些资源还需要内核支持:

sudo sysctl -w fs.file-max=1000000

永久生效:

echo "fs.file-max=1000000" | sudo tee -a /etc/sysctl.conf
sudo sysctl -p

五、常见问题排查

1. su / sudo 后 ulimit 没变?

  • 使用 su - 用户名(登录 shell)
  • 或检查 PAM 是否生效

2. Docker 容器不生效?

需在宿主机或 docker run 中设置:

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

总结速查表

场景 方法
临时 ulimit
用户 /etc/security/limits.conf
服务 systemctl edit
系统 sysctl / system.conf

如果你能说明 具体是哪种资源(如 nofile / nproc)和用途(SSH / 服务 / Docker),我可以给你更精确的配置。

0