MeWrite Docs

Nginx: 502 Bad Gateway

Nginx 502エラーの解決方法

概要

Nginxがプロキシとして動作中にバックエンドサーバーから無効な応答を受け取った場合に発生するエラーです。

エラーメッセージ

502 Bad Gateway
nginx/1.18.0

ログ:

upstream prematurely closed connection while reading response header from upstream

原因

  1. バックエンドダウン: アプリケーションサーバーが停止
  2. タイムアウト: バックエンドの応答が遅い
  3. ソケット接続: Unixソケットのパスが間違い
  4. リソース不足: メモリやファイルディスクリプタ枯渇

解決策

1. バックエンド確認

1
2
3
4
5
6
# プロセス確認
ps aux | grep node
ps aux | grep gunicorn

# ログ確認
tail -f /var/log/nginx/error.log

2. Nginx設定

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
upstream backend {
    server 127.0.0.1:3000;
    keepalive 32;
}

server {
    location / {
        proxy_pass http://backend;
        proxy_connect_timeout 60s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;
        proxy_buffer_size 128k;
        proxy_buffers 4 256k;
    }
}

3. PHP-FPM設定

1
2
3
4
location ~ \.php$ {
    fastcgi_pass unix:/var/run/php/php8.1-fpm.sock;
    fastcgi_read_timeout 300;
}

よくある間違い

  • Unixソケットのパーミッション
  • タイムアウト値がバックエンドより短い

Nginx の他のエラー

最終更新: 2025-12-09