Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> Linux 教學

Linux「Too many open files」錯誤徹底解決指南:臨時與永久修復方案

編輯:Linux 教學

「Too many open files」是 Linux 系統常見的資源耗盡錯誤。當進程打開的文件描述符數量超過系統或使用者層級的限制時,核心會拋出此異常,導致服務無法建立新連線、寫入日誌甚至直接崩潰。本文整理從臨時緩解到永久生效的完整解決路徑,助您快速恢復服務穩定。

錯誤現象

典型場景:Java 應用(如 Resin、Tomcat)、高併發 Web 服務(Nginx、Apache)在流量尖峰時出現報錯,日誌中明顯提示 Too many open files。

一、臨時解決(重啟服務前有效)

在當前 Shell 會話中執行:

ulimit -n 65535

隨後重啟目標服務(如 systemctl restart resin)。注意:需切換至服務實際運行的使用者身份執行 ulimit -n 驗證限制是否已生效。

二、永久生效方案

方法一:修改 /etc/profile(不推薦用於生產環境)

echo "ulimit -n 65535" >> /etc/profile
source /etc/profile

缺點:普通使用者登入時可能因權限不足報錯,且對已運行的 systemd 服務不生效。

方法二:配置 /etc/security/limits.conf(推薦標準做法)

編輯檔案,於末尾加入:

* 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)。

方法三:針對 Systemd 服務(現代 Linux 必做)

編輯服務單元檔(如 /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'

避坑提醒

  • 修改任何配置後,必須完全重啟應用進程(非 reload),才會繼承新限制。
  • 若為 Docker 容器,需在 docker run 參數加入 --ulimit nofile=65535:65535。
  • 系統全域上限受 /proc/sys/fs/file-max 限制,如需更高值請同步調整 sysctl -w fs.file-max=2097152 並寫入 /etc/sysctl.conf。
Copyright © Windows教程網 All Rights Reserved