在 Debian 系统中,ulimit 用于控制单个进程(或 shell 会话)可使用的系统资源,如文件描述符数、进程数、栈大小等。优化 ulimit 通常是为了提高高并发服务能力(如 Web 服务器、数据库、消息队列等)。
下面从 查看 → 临时修改 → 永久修改 → 系统级优化 四个方面说明。
ulimit -a
常见关键项:
-n:打开文件描述符数(file descriptors)-u:用户最大进程数-s:栈大小-c:core 文件大小查看某一项:
ulimit -n
ulimit -n 65535
ulimit -u 4096
⚠️ 只对当前 shell 及其子进程有效,重启失效。
/etc/security/limits.conf编辑文件:
sudo vim /etc/security/limits.conf
示例(针对用户或组):
* soft nofile 65535
* hard nofile 65535
* soft nproc 4096
* hard nproc 4096
说明:
soft:警告值(可超过,但会提示)hard:硬限制(不可超过)* 表示所有用户,也可指定用户名,如 www-data✅ 需要 重新登录 或重启才能生效。
Debian 使用 systemd 后,limits.conf 对服务可能不生效
sudo systemctl edit nginx
添加:
[Service]
LimitNOFILE=65535
LimitNPROC=4096
然后:
sudo systemctl daemon-reload
sudo systemctl restart nginx
sudo vim /etc/systemd/system.conf
修改或取消注释:
DefaultLimitNOFILE=65535
DefaultLimitNPROC=4096
sudo systemctl daemon-reexec
ulimit 受内核参数限制,常见优化:
sudo sysctl -w fs.file-max=1000000
永久生效:
echo "fs.file-max=1000000" | sudo tee -a /etc/sysctl.conf
sudo sysctl -p
查看:
cat /proc/sys/fs/file-max
nofile 65535
nproc 4096
nofile 1048576
在 docker run 中:
--ulimit nofile=65535:65535
bash: ulimit: open files: cannot modify limitToo many open files如果你能告诉我:
我可以给你更精确的配置示例。