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

Nginx 錯誤「readv() failed (104: Connection reset by peer)」解決方案

編輯:關於伺服器

錯誤現象

[error] readv() failed (104: Connection reset by peer) while reading upstream,
client: x.x.x.x, server: host.tld, request: "POST /script.php ..."

根因分析

  • 104 Connection reset by peer:上游 (PHP-FPM) 主動關閉連線
  • 常見於:PHP 腳本執行時間超過 request_terminate_timeout,FPM 強制殺掉 Worker 進程
  • 導致 Nginx 讀取上游回應時發現連線已斷開

核心解決:調大 PHP-FPM 超時設定

# php-fpm.conf 或 www.conf
request_terminate_timeout = 600  # 秒,預設通常 30s 或 0(關閉)

# 同步調整 Nginx 超時
# nginx.conf http/server/location 區塊
fastcgi_read_timeout 600s;
proxy_read_timeout 600s;

完整超時參數對照表

層級參數建議值說明
PHP-FPMrequest_terminate_timeout600s單一請求硬性終止時間
PHP-FPMrequest_slowlog_timeout10s慢日誌觸發閾值
PHPmax_execution_time300php.ini 腳本執行上限
Nginxfastcgi_read_timeout600s等待 FastCGI 回應
Nginxproxy_read_timeout600s反向代理等待上游
Nginxclient_body_timeout60s讀取請求體超時

進階排查:為什麼腳本跑那麼久?

  1. 開啟慢日誌分析:
    slowlog = /var/log/php-fpm-slow.log
    request_slowlog_timeout = 5s
  2. 使用 xdebug / tideways / blackfire 剖析效能瓶頸
  3. 常見慢因:
    • 資料庫無索引/鎖等待
    • 外部 API 呼叫無超時設定
    • 大量資料記憶體運算
    • 死循環/遞迴無終止條件

最佳實踐

不要只調大超時!**必須**找出慢查詢根因優化。超時設定是安全網,不是解決方案。長跑任務請改用佇列 (Redis/RabbitMQ) + Worker 非同步處理,HTTP 請求只負責分發任務並即時回應。

驗證修復

# 重載配置
systemctl reload php-fpm
nginx -s reload

# 模擬長跑請求測試
curl --max-time 610 "https://example.com/long_task.php"
# 應正常返回結果,而非 502/504
Copyright © Windows教程網 All Rights Reserved