温馨提示×

debian ulimit如何调优

小樊
34
2026-09-16 03:00:46
栏目: 智能运维

在 Debian(以及大多数 Linux 发行版)中,ulimit 用于控制单个进程可使用的系统资源上限,如文件描述符数、进程数、内存、栈大小等。调优 ulimit 通常是为了:

  • 提高高并发服务(如 Nginx、MySQL、Redis)的连接能力
  • 防止程序因资源耗尽而崩溃
  • 避免“Too many open files”等问题

下面按使用场景系统说明如何在 Debian 上调优 ulimit


一、查看当前 ulimit 设置

ulimit -a

常用项说明:

-n  open files
-u  max user processes
-s  stack size
-c  core file size
-m  resident set size (常忽略)
-v  virtual memory

查看某一项:

ulimit -n
ulimit -u

二、临时调整(仅当前 shell / 进程)

ulimit -n 65536
ulimit -u 4096

⚠️ 只在当前 shell 生效,重启或新登录失效。


三、永久调整(推荐做法)

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

sudo vim /etc/security/limits.conf

示例(针对用户或组):

*               soft    nofile          65536
*               hard    nofile          65536
*               soft    nproc          4096
*               hard    nproc          4096

说明:

  • soft:警告值(可临时超过)
  • hard:硬上限(不可超过)
  • nofile:打开文件数
  • nproc:进程数
  • * 表示所有用户,也可写具体用户名

✅ 需要 PAM 支持(Debian 默认支持)

确保以下文件包含:

session required pam_limits.so

通常在:

  • /etc/pam.d/common-session
  • /etc/pam.d/sshd

2️⃣ systemd 服务的特殊限制(非常重要)

limits.conf 对 systemd 启动的服务无效!

查看服务当前限制

systemctl show nginx | grep Limit

修改服务 ulimit(推荐)

编辑 service 文件:

sudo systemctl edit nginx

写入:

[Service]
LimitNOFILE=65536
LimitNPROC=4096

重新加载:

sudo systemctl daemon-reload
sudo systemctl restart nginx

四、系统级文件描述符上限

即使 ulimit -n 调大,系统总 fd 也有限制。

查看

cat /proc/sys/fs/file-max

修改

sudo vim /etc/sysctl.conf
fs.file-max = 2097152

生效:

sudo sysctl -p

五、常见调优场景示例

✅ Web 服务器(Nginx / Apache)

nofile 65535
nproc  4096

✅ 数据库(MySQL / PostgreSQL)

nofile 100000
nproc  8192

✅ 高并发中间件(Redis / Kafka)

nofile 1048576

六、验证是否生效

# 登录后
ulimit -n

# 查看某进程
cat /proc/<pid>/limits

七、常见坑总结

limits.conf 不生效
→ 服务由 systemd 启动

❌ 改了不生效
→ 没重新登录 / 没重启服务

❌ “Too many open files”
→ 检查 nofile + fs.file-max


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

  • Debian 版本(11 / 12)
  • 跑的是什么服务(Nginx / Docker / MySQL)
  • 当前报错信息

我可以给你一套针对性的 ulimit 调优方案

0