nginx/Apache: 502 Bad Gateway

2022010608:11


502 Bad Gateway 的狀況很多種
通常會是後端 (upstream) 的 server 異常造成

這裡記錄個人遇到的問題、解法


我的架構大概


前端 nginx 常常出現 502 Bad Gateway 訊息時, nginx 所記錄的內容:
2021/12/28 13:23:15 [error] 1598#1598: *22104 upstream prematurely closed connection while reading response header
from upstream, client: 150.11.xx.xx, server: test.abc.cc, request: "GET /st/st.php HTTP/2.0",
upstream: "http://192.168.0.211:80/st/st.php",
host: "test.nidbox.cc", referrer: "http://test.abc.cc/st/st.php"

而後端 (上游 upstream) Apache httpd 同時會出現 error:
[Tue Dec 28 21:34:12.441197 2021] [core:notice] [pid 2472:tid 140443206428480] 
AH00052: child pid 31990 exit signal Segmentation fault (11)

查了好久,我的問題 發生在 Apache httpd 設定
mpm 中的被設定為:(包含 prefork/event/worker三種模式)

MaxConnectionsPerChild   10  (系統原始設定是 0)

MaxConnectionsPerChild  N:
   maximum number of connections a server process serves
   0 表示 process 永不消毀 (不建議設定為 0)
   >0 指 httpd child process(子行程) 在處理了超過該數值的 request 後,就會自動銷毀 以避免記憶體洩漏、耗盡記憶體的問題

因為被設為 10,所以很大的機率出現問題
加大這個數值即可解決。