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
- 1Check Nginx error log: 'tail -50 /var/log/nginx/error.log' — look for upstream connection errors
- 2Verify upstream is running: 'systemctl status php-fpm' or 'systemctl status your-app'
- 3Check socket permissions: 'ls -la /run/php/php-fpm.sock' — Nginx user must have read/write access
- 4Increase buffer and timeout: 'proxy_buffer_size 128k; proxy_buffers 4 256k; proxy_read_timeout 300;'
- 5Test upstream directly: 'curl http://127.0.0.1:3000' to verify the application responds
Tags
nginx502bad-gatewayupstreamproxy
More in Web Server
linux-nginx-error-codesLinux Nginx Error Codes — 502, 504, 413 & Upstream Failures
Errorlinux-apache-error-codesLinux Apache Error Codes — AH01630, AH00558 & Module Errors
Warninglinux-nginx-common-errorsNginx Common Errors — Configuration Test Failed and Upstream Timeout
Errorlinux-nginx-504-gateway-timeoutNginx 504 Gateway Timeout — Slow Upstream Response and Timeout Configuration
Errorlinux-apache-mod-rewrite-errorsApache mod_rewrite Errors — URL Rewriting, .htaccess, and Redirect Loop Issues
Warninglinux-reverse-proxy-errorsReverse Proxy Errors — SSL Termination, Header Forwarding, and Backend Connection Issues
WarningFrequently 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.