萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 伺服器教學

Linux "too many open files" 解決方案:ulimit 與 limits.conf 永久調整

現象

程式啟動失敗,日誌顯示 too many open files。預設單進程開啟檔案描述符上限為 1024。

查看目前限制


ulimit -a
# open files (-n) 1024

臨時調整 (當前 Shell 及其子進程有效)


ulimit -n 65535
# 若提示 "Operation not permitted",需先以 root 調整硬限制

永久調整 (需重新登入生效)

  1. 編輯 /etc/security/limits.conf:
    
    *           soft    nofile          65535
    *           hard    nofile          65535
    *           soft    nproc           65535
    *           hard    nproc           65535
    root        soft    nofile          65535
    root        hard    nofile          65535
    

    soft 為當前生效值,hard 為上限;普通用戶可降低 soft 不能超過 hard,root 可調整 hard。

  2. 確保 PAM 載入 limits 模組:/etc/pam.d/login、/etc/pam.d/sshd、/etc/pam.d/su 包含:
    
    session required pam_limits.so
    
  3. systemd 服務單獨設定 (如 Nginx、MySQL、Java 應用):
    
    # /etc/systemd/system/nginx.service.d/limits.conf
    [Service]
    LimitNOFILE=65535
    LimitNPROC=65535
    
    執行 systemctl daemon-reload && systemctl restart nginx。

驗證


# 重新登入後
ulimit -n
# 65535

# 檢查進程實際限制
cat /proc//limits | grep "Max open files"

常見誤區

  • 只改 limits.conf 未重新登入 (SSH 重新連線、su - user)。
  • systemd 服務未加 LimitNOFILE 仍受預設 1024 限制。
  • Docker 容器需在 docker run --ulimit nofile=65535:65535 或 Daemon 設定 default-ulimits。
copyright © 萬盛學電腦網 all rights reserved