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

Nginx 502 Bad Gateway 與 504 Gateway Timeout 根因分析與調優方案

編輯:關於伺服器

錯誤定義

錯誤含義主要關聯配置
502 Bad GatewayPHP-CGI 進程啟動但異常終止 (讀取資源失敗、超時、段錯誤)php-fpm.conf
504 Gateway TimeoutNginx 等待 PHP-CGI 回應超時,或無可用 PHP-CGI 進程 (佇列滿)nginx.conf

核心參數調優

php-fpm.conf 關鍵參數

40
10
5
20
1000
900s  
  • max_children:依記憶體計算。單進程 ~20-30MB,1GB 記憶體建議 30-40。
  • request_terminate_timeout:長跑腳本需放寬,防止 502。短請求建議 30-60s。
  • max_requests:定期重啟進程釋放記憶體洩漏,建議 500-2000。

nginx.conf FastCGI 參數

fastcgi_connect_timeout 600;
fastcgi_send_timeout 600;
fastcgi_read_timeout 600;
fastcgi_buffer_size 256k;
fastcgi_buffers 16 256k;
fastcgi_busy_buffers_size 512k;
fastcgi_temp_file_write_size 512k;
fastcgi_intercept_errors on;
  • 三個 timeout 必須大於 php-fpm 的 request_terminate_timeout。
  • 緩衝區放大可減少臨時檔寫入,提升大回應效能。

臨時緩解方案 (生產環境應盡快根治)

  1. 調大 pm.max_children、request_terminate_timeout。
  2. 調大 Nginx FastCGI timeout 與 buffer。
  3. 重啟 php-fpm:service php-fpm reload (平滑重啟)。

長期穩定策略

  • Crontab 定時平滑重啟:0 3 * * * /usr/local/php/sbin/php-fpm reload (低峰期)。
  • 監控與告警:監控 pm.max_children 使用率、slowlog、記憶體增長趨勢。
  • 程式碼層面:修復死循環、大記憶體分配、資料庫慢查詢。
  • 架構層面:引入 Redis 快取、訊息佇列削峰、PHP-FPM 多池隔離業務。
Copyright © Windows教程網 All Rights Reserved