深色模式
资源限制 ulimit
摘要:运行服务的账户连不上新连接、报打开文件过多?本文为服务账户调大 nofile 限制,并让 systemd 服务也吃到新值。前提:root/sudo,配合 sysctl 篇的系统上限。
适用环境
bash
ulimit -n # 当前 shell 的软限制
ulimit -Hn # 硬限制(不能超过)
id appuser 2>/dev/null || useradd appuser # 假设有服务账户1
2
3
2
3
一、临时调整当前会话
bash
ulimit -n 65536 # 调到 65536(不能超过硬限制)
ulimit -n # 确认生效(仅本会话)1
2
2
二、为账户永久生效(limits.conf)
bash
cat >> /etc/security/limits.d/99-appuser.conf <<'EOF'
appuser soft nofile 65536
appuser hard nofile 65536
EOF
# 重新登录 appuser 后 `ulimit -n` 即生效1
2
3
4
5
2
3
4
5
三、systemd 服务也要单独设
注意
limits.conf 对 systemd 管理的服务不生效!必须在 service 文件里加 LimitNOFILE。
bash
# 在 /etc/systemd/system/yourapp.service 的 [Service] 段加:
# LimitNOFILE=65536
systemctl daemon-reload
systemctl restart yourapp
# 验证:
cat /proc/$(pgrep -u appuser yourapp)/limits | grep "Max open files"1
2
3
4
5
6
2
3
4
5
6
验证
- [ ] 重新登录 appuser 后
ulimit -n显示 65536 - [ ] systemd 服务的
/proc/<pid>/limits中 Max open files 已变大 - [ ] 高并发下不再报 "Too many open files"
常见坑
- limits.conf 管不到 systemd 服务:这是最常见漏点,必须设
LimitNOFILE。 - 硬限制挡路:调软限制前先确认硬限制够大,否则报 "Operation not permitted"。
- 改完要重登录:limits.conf 在登录时读取,当前 shell 不生效。
- nproc 也要看:除 nofile 外,线程多时还需调
nproc。