「Too many open files」是 Linux 系統常見的資源耗盡錯誤。當進程打開的文件描述符數量超過系統或使用者層級的限制時,核心會拋出此異常,導致服務無法建立新連線、寫入日誌甚至直接崩潰。本文整理從臨時緩解到永久生效的完整解決路徑,助您快速恢復服務穩定。
典型場景:Java 應用(如 Resin、Tomcat)、高併發 Web 服務(Nginx、Apache)在流量尖峰時出現報錯,日誌中明顯提示 Too many open files。
在當前 Shell 會話中執行:
ulimit -n 65535
隨後重啟目標服務(如 systemctl restart resin)。注意:需切換至服務實際運行的使用者身份執行 ulimit -n 驗證限制是否已生效。
echo "ulimit -n 65535" >> /etc/profile
source /etc/profile
缺點:普通使用者登入時可能因權限不足報錯,且對已運行的 systemd 服務不生效。
編輯檔案,於末尾加入:
* soft noproc 65535
* hard noproc 65535
* soft nofile 65535
* hard nofile 65535
或一次性寫入:
cat >> /etc/security/limits.conf <<'EOF'
* soft noproc 65535
* hard noproc 65535
* soft nofile 65535
* hard nofile 65535
EOF
關鍵說明:
nofile:單一進程最大可開啟文件描述符數(含 Socket、管道等)。noproc:使用者最大進程/線程數,防止 Fork 炸彈。soft 為預設限制,hard 為上限(root 可突破 soft 至 hard)。編輯服務單元檔(如 /etc/systemd/system/resin.service 或執行 systemctl edit resin),在 [Service] 區塊加入:
LimitNOFILE=65535
LimitNPROC=65535
重載並重啟:
systemctl daemon-reload
systemctl restart resin
進入服務進程環境檢查:
cat /proc/$(pgrep -f resin)/limits | grep -E 'Max open files|Max processes'
docker run 參數加入 --ulimit nofile=65535:65535。/proc/sys/fs/file-max 限制,如需更高值請同步調整 sysctl -w fs.file-max=2097152 並寫入 /etc/sysctl.conf。