在 Debian(以及大多数 Linux 发行版)中,ulimit 用于控制用户进程可使用的系统资源上限,例如打开文件数、进程数、栈大小等。优化 ulimit 配置,通常需要结合使用场景(如高并发服务、数据库、开发环境)和配置方式(临时 / 永久、用户级 / 系统级)。
下面从 概念 → 查看 → 临时设置 → 永久优化 → 常见场景建议 详细说明。
ulimit 分为两类:
常见重要参数:
| 参数 | 含义 |
|---|---|
-n |
最大打开文件数(file descriptors) |
-u |
最大用户进程数 |
-s |
栈大小 |
-c |
core 文件大小 |
-m / -v |
内存限制(部分系统忽略) |
ulimit -a
查看某个具体限制:
ulimit -n # 打开文件数
ulimit -u # 进程数
查看系统级限制:
cat /proc/sys/fs/file-max
ulimit -n 65536
ulimit -u 4096
⚠️ 重启或新登录后失效。
/etc/security/limits.conf这是 最常见、最标准的做法。
编辑文件:
sudo vim /etc/security/limits.conf
示例(为用户 www 或服务账户优化):
www soft nofile 65536
www hard nofile 65536
www soft nproc 4096
www hard nproc 4096
或对所有用户:
* soft nofile 65536
* hard nofile 65536
✅ 生效条件:
/etc/pam.d/common-session 包含:session required pam_limits.so
Debian 默认使用 systemd,很多服务 不读取 limits.conf。
sudo systemctl edit nginx
写入:
[Service]
LimitNOFILE=65536
LimitNPROC=4096
重新加载:
sudo systemctl daemon-reload
sudo systemctl restart nginx
sudo vim /etc/systemd/system.conf
DefaultLimitNOFILE=65536
DefaultLimitNPROC=4096
sudo systemctl daemon-reexec
即使 ulimit 调高,内核也要允许:
cat /proc/sys/fs/file-max
临时:
sudo sysctl -w fs.file-max=1000000
永久:
sudo vim /etc/sysctl.conf
fs.file-max = 1000000
sudo sysctl -p
nofile 65535~1000000
nproc 4096~8192
nofile 100000+
nproc 未限制或高
stack 足够大(默认一般 OK)
nofile 适当提高
docker run --ulimit nofile=65536:65536
用户级 → limits.conf 服务级 → systemd 系统级 → sysctl 容器 → 运行时参数
如果你能告诉我:
我可以给你一套可直接用的配置模板。