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

Nginx 500 Internal Server Error 根因全景圖:從文件句柄、併發配置到磁碟空間系統性排查

編輯:關於伺服器

Nginx 返回 500 錯誤原因極其多樣,但 80% 集中於「資源耗盡」與「配置錯誤」兩大類。本文彙總高頻根因、驗證方法與生產級調優參數,建立標準化排查體系。

核心根因分類

類別典型癥狀驗證命令解決方向
文件描述符耗盡高併發下突發 500,error.log 見 accept() failed (24: Too many open files)ulimit -n, cat /proc/$PID/limits調大系統/進程/Worker 句柄上限
Worker 連接數不足併發上升時 500,worker_connections are not enoughgrep worker_connections nginx.conf調大 worker_connections、worker_processes
磁碟空間/Inode 滿寫日志/緩存/上傳失敗,No space left on devicedf -h, df -i清理日誌、啟用 logrotate、擴容
配置語法/邏輯錯誤reload 後 500,rewrite 循環、變量未定義nginx -t, error.log修正 rewrite 規則、補全變量
上游服務異常代理/後端超時、拒絕連線、返回非 HTTPcurl -v 上游IP, 後端日誌檢查 PHP-FPM、資料庫、微服務狀態
權限/路徑錯誤靜態文件 403/500,Permission deniedls -l, namei -l 路徑修正目錄權限、root/alias 指向

系統級句柄調優 (生產標準)

1. 永久生效 (需重啟)


# /etc/security/limits.conf
* soft nofile 65535
* hard nofile 65535

# /etc/sysctl.conf
fs.file-max = 655350
sysctl -p  # 即時生效內核參數

2. Nginx 進程級句柄 (無需重啟系統)


# nginx.conf main context
worker_rlimit_nofile 65535;

events {
    worker_connections 65535;  # 單 Worker 最大連接數
    use epoll;                 # Linux 高效事件模型
    multi_accept on;           # 採集多連接
}

3. 驗證生效


# 查看 Master 進程限制
cat /proc/$(cat /usr/local/nginx/logs/nginx.pid)/limits | grep 'Max open files'
# 輸出應為 65535 65535

併發架構調優


worker_processes auto;           # 自動匹配 CPU 核心數
worker_cpu_affinity auto;        # 綁定 CPU 核心 (Linux 2.6+)

events {
    worker_connections 20480;    # 總併發 ≈ worker_processes × worker_connections
}

http {
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    keepalive_requests 1000;
}

磁碟空間守護

  1. 關閉非必要 access_log:access_log off; (健康檢查、內部 API)。
  2. 配置 logrotate 每日切割、壓縮、保留 7 天:

/usr/local/nginx/logs/*.log {
    daily
    rotate 7
    compress
    delaycompress
    missingok
    notifempty
    sharedscripts
    postrotate
        /usr/local/nginx/sbin/nginx -s reopen
    endscript
}

排查 SOP (5 分鐘定位)

  1. tail -f error.log 實時看錯誤碼 (24/11/13/98 等 errno)。
  2. ulimit -n + worker_rlimit_nofile 對比,確認句柄生效。
  3. df -h /var/log/nginx 確認日誌分區剩餘 > 20%。
  4. nginx -t 驗證配置語法。
  5. curl -v https://127.0.0.1/health 直連後端排除上游問題。

系統化建立「句柄→併發→磁碟→配置→上游」排查鏈路,將 500 錯誤 MTTR (平均修復時間) 壓縮至 10 分鐘內。

Copyright © Windows教程網 All Rights Reserved