在 Debian 系统中优化 ulimit(用户资源限制)通常用于提升高并发服务、数据库、反向代理等场景的稳定性。下面从概念 → 查看 → 临时修改 → 永久修改 → 常见优化建议系统说明。
ulimit 分为两类:
常用资源类型:
-n:打开文件描述符数(最重要)-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
示例(对所有用户):
* soft nofile 65536
* hard nofile 65536
* soft nproc 4096
* hard nproc 4096
指定用户(如 www-data):
www-data soft nofile 100000
www-data hard nofile 100000
✅ 需要 pam_limits.so 支持(默认已启用)
如果是 systemd 启动的服务(Nginx / MySQL / Redis):
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
sudo vim /etc/sysctl.conf
fs.file-max = 1000000
生效:
sudo sysctl -p
nofile 65535 ~ 100000
nproc 4096
nofile 100000+
nproc 8192
--ulimit nofile=65536:65536
cat /proc/<pid>/limits
或:
ps aux | grep nginx
cat /proc/$(pgrep nginx | head -1)/limits
❌ 改了 limits.conf 但服务没生效
→ 多半是 systemd 覆盖
❌ Docker 容器不生效
→ 容器有独立 ulimit
❌ SSH 登录不生效
→ 确保 UsePAM yes
如果你能告诉我:
我可以给你精准配置方案。