在 Debian(以及大多数 Linux 发行版)上,ulimit 用于限制单个用户/进程可使用的系统资源。优化 ulimit 通常是为了:
下面按使用场景给你一套常用优化方案。
ulimit -a
常见关键项:
-n:open files(文件描述符)-u:max user processes-c:core file size-s:stack sizeulimit -n 65535
ul ulimit -u 4096
⚠️ 重启或新开 shell 失效
/etc/security/limits.confsudo vim /etc/security/limits.conf
示例(针对所有用户或指定用户):
* soft nofile 65535
* hard nofile 65535
* soft nproc 4096
* hard nproc 4096
或针对服务用户(如 www-data):
www-data soft nofile 100000
www-data hard nofile 100000
✅ 需要 PAM 登录 才生效(SSH / 桌面 / su)
检查:
grep pam_limits /etc/pam.d/common-session
应有:
session required pam_limits.so
如果没有,手动添加。
limits.conf 对 systemd 服务无效!
sudo systemctl edit nginx
添加:
[Service]
LimitNOFILE=100000
LimitNPROC=4096
然后:
sudo systemctl daemon-reload
sudo systemctl restart nginx
sudo vim /etc/systemd/system.conf
DefaultLimitNOFILE=100000
DefaultLimitNPROC=4096
查看:
cat /proc/sys/fs/file-max
临时:
sysctl -w fs.file-max=2000000
永久:
sudo vim /etc/sysctl.conf
fs.file-max = 2000000
sysctl -p
| 服务 | nofile | nproc |
|---|---|---|
| Nginx | 65535–100000 | 4096 |
| MySQL | 65535+ | 4096 |
| Redis | 65535 | 4096 |
| Java | 100000+ | 4096 |
cat /proc/<pid>/limits
例如:
cat /proc/$(pgrep nginx | head -1)/limits
hard ≥ soft--ulimit如果你能告诉我:
我可以给你更精准的配置模板。