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

Nginx 502 Bad Gateway 深度排查與效能調優實戰

編輯:Linux 教學

Nginx 回傳 502 Bad Gateway 代表上游伺服器回應異常或逾時。本文從 PHP-FPM 程序管理、Nginx 代理逾時參數、CPU 親和性綁定、MySQL 後端優化、內核網路參數調整七大面向,提供系統化排查與調優清單。

一、PHP-FPM 核心參數調校

參數建議值/策略說明
request_terminate_timeout30s~60s單一請求硬性終止時間,防止殭屍進程佔用槽位
pm.max_children(總記憶體 - 系統保留) / 單進程記憶體靜態模式建議固定值;動態模式設定 pm.start_servers、pm.min_spare_servers、pm.max_spare_servers
pm.max_requests500~1000進程重生機制,緩解記憶體洩漏
pm.status_path/status啟用狀態頁配合監控(Prometheus/Grafana)

二、Nginx FastCGI/Proxy 逾時參數對照表

# FastCGI 方向
fastcgi_connect_timeout 6s;   # 連線上游建立連線
fastcgi_send_timeout 60s;     # 傳送請求到上游
fastcgi_read_timeout 60s;     # 讀取上游回應(關鍵)

# Proxy 方向
proxy_connect_timeout 6s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;

若上游處理耗時不可預期,建議搭配 proxy_buffering off 並調大 proxy_buffers。

三、CPU 親和性與中斷平衡

# nginx.conf
worker_processes auto;
worker_cpu_affinity auto;  # 1.9+ 版本自動綁定

# 或手動綁定(假設 8 核,保留 CPU0 處理網卡中斷)
worker_cpu_affinity 00000001 00000010 00000100 00001000 00010000 00100000 01000000 10000000;

搭配 irqbalance 服務將網卡中斷分散至非 Nginx 工作核心,降低封包處理延遲。

四、MySQL 後端常見瓶頸排查

  • 慢查詢:long_query_time = 1 + pt-query-digest 分析
  • 連線池耗盡:調整 max_connections、啟用 ProxySQL 連線多工
  • 鎖競爭:SHOW ENGINE INNODB STATUS 觀察 LATEST DETECTED DEADLOCK
  • I/O 飽和:innodb_io_capacity、innodb_flush_method=O_DIRECT

五、Linux 內核網路參數優化(針對高併發)

/etc/sysctl.d/99-nginx-tuning.conf
net.core.somaxconn = 65535
net.core.netdev_max_backlog = 65535
net.ipv4.tcp_max_syn_backlog = 65535
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_fin_timeout = 15
net.ipv4.tcp_keepalive_time = 300
net.ipv4.ip_local_port_range = 1024 65535
net.netfilter.nf_conntrack_max = 1000000
net.netfilter.nf_conntrack_tcp_timeout_established = 1200

套用:sysctl --system。注意:nf_conntrack 表滿導致封包丟棄(dmesg 出現 nf_conntrack: table full, dropping packet)非單純 ip_conntrack_max 過小,常為連線追蹤模組效能不足,建議關閉不必要的連線追蹤或升級內核至 5.x 以上。

六、升級內核與啟用 BBR 擁塞控制

# Debian/Ubuntu
apt install --install-recommends linux-generic-hwe-22.04
# 啟用 BBR
echo "net.core.default_qdisc=fq" >> /etc/sysctl.d/99-bbr.conf
echo "net.ipv4.tcp_congestion_control=bbr" >> /etc/sysctl.d/99-bbr.conf
sysctl --system

BBR 顯著降低高延遲、高丟包鏈路的傳輸逾時,間接減少 502 發生率。

七、快速定位 502 根因檢查清單

  1. tail -f /var/log/nginx/error.log | grep -i "upstream"
  2. systemctl status php-fpm 檢查進程數、重啟次數
  3. netstat -antp | grep :9000 確認上游監聽正常
  4. curl -o /dev/null -s -w "%{http_code}\\n" https://127.0.0.1/status 監控 PHP-FPM 狀態頁
  5. dmesg -T | grep -i -e oom -e nf_conntrack 排除核心層面資源耗盡

系統化調優非一次性動作,建議建立基準效能基線(wrk/ab 壓測),逐項變更並回歸測試,方能穩定消除 502 錯誤。

Copyright © Windows教程網 All Rights Reserved