悠悠楠杉
网站页面
上周运维团队凌晨接到报警,某核心微服务突然拒绝连接。通过ss -s查看发现"orphaned"连接数爆增,进一步检查dmesg看到大量"Too many open files"错误——典型的文件句柄耗尽场景。这种问题在数据库、消息队列等高并发服务中尤为常见,而正确的ulimit设置就是解决方案。
bash
# 查看当前会话限制
ulimit -n/proc/sys/fs/file-max:系统总文件句柄数/proc/sys/fs/nr_open:单进程最大限制bash
cat /proc/sys/fs/file-nr
bash
sysctl -w fs.file-max=1000000
echo "fs.file-max = 1000000" >> /etc/sysctl.conf
sysctl -p
编辑/etc/security/limits.conf:
conf
* soft nofile 65535
* hard nofile 100000
nginx soft nofile 100000
nginx hard nofile 500000
注意:需要重新登录会话生效!
对于现代Linux系统,还需要修改服务单元:bash
systemctl edit nginx
[Service]
LimitNOFILE=102400
bash
LimitNOFILE=128000
LimitMEMLOCK=infinity
除修改limits.conf外,还需:bash
-XX:-MaxFDLimit
bash
cat /proc/<PID>/limitsbash
lsof -n | wc -lbash
lsof -u nginx | awk '{print $9}' | sort | uniq -c | sort -nr总结:合理的文件句柄设置需要结合业务特性,通过"监控-调整-验证"闭环持续优化。记住,系统调优不是一劳永逸的工作,而是伴随业务增长的持续过程。