Error Codes Wiki

Nginx 502 Bad Gateway — Upstream Server Connection and Proxy Errors

Errorweb server

Overview

Fix Nginx 502 Bad Gateway errors caused by upstream application crashes, socket connection failures, timeout issues, and misconfigured proxy settings.

Key Details

  • 502 Bad Gateway means Nginx received an invalid response from the upstream server it proxied to
  • The upstream server (PHP-FPM, Node.js, Python, Java) may have crashed, timed out, or refused the connection
  • Nginx error log (/var/log/nginx/error.log) contains the specific upstream failure reason
  • Common upstream errors: 'connect() failed', 'upstream prematurely closed connection', 'no live upstreams'
  • Socket permission issues prevent Nginx from connecting to Unix socket upstreams

Common Causes

  • Upstream application (PHP-FPM, Node.js, Gunicorn) crashed or is not running
  • Unix socket permissions preventing Nginx worker from connecting to the upstream
  • Upstream response exceeding Nginx buffer sizes causing invalid response parsing
  • Upstream application timeout — response takes longer than proxy_read_timeout

Steps

  1. 1Check Nginx error log: 'tail -50 /var/log/nginx/error.log' — look for upstream connection errors
  2. 2Verify upstream is running: 'systemctl status php-fpm' or 'systemctl status your-app'
  3. 3Check socket permissions: 'ls -la /run/php/php-fpm.sock' — Nginx user must have read/write access
  4. 4Increase buffer and timeout: 'proxy_buffer_size 128k; proxy_buffers 4 256k; proxy_read_timeout 300;'
  5. 5Test upstream directly: 'curl http://127.0.0.1:3000' to verify the application responds

Tags

nginx502bad-gatewayupstreamproxy

More in Web Server

Frequently Asked Questions

Check /var/log/nginx/error.log. The error line shows the upstream address, the error type (connect failed, timeout, prematurely closed), and the request URL that triggered it.