Nginx 502 Bad Gateway: Causes and Fixes on Linux (Upstream, PHP-FPM, Timeouts)

nginx 502 bad gateway - custom-nginx502-featured.png

A 502 Bad Gateway means Nginx acted as a gateway but could not get a valid response from the upstream app — PHP-FPM, Node, Gunicorn, or another proxy target. The fix is almost always on the upstream side or in the proxy configuration.

This guide complements Nginx reverse proxy and
Nginx vs Apache.

What 502 Means

Nginx is up; the backend is not answering correctly — connection refused, timeout, or invalid response.

502 path
edge vs upstream

Confirm the Upstream Is Listening

Match proxy_pass or fastcgi_pass to a real port or socket.

bashchecks
sudo ss -tlnp | grep -E ':3000|:9000'
systemctl status php8.2-fpm nginx --no-pager
upstream
ss and systemctl

Read error.log First

Look for connect() failed, upstream prematurely closed, or timeout messages with timestamps.

bashlogs
sudo tail -50 /var/log/nginx/error.log
journalctl -u php8.2-fpm --since "10 min ago" --no-pager | tail
error.log
journalctl

Tune Proxy Timeouts

Slow APIs may need higher proxy_read_timeout. Do not set infinite timeouts — fix the slow query instead.

nginxlocation block excerpt
proxy_read_timeout 120s;
proxy_connect_timeout 10s;
timeouts
proxy_* directives

Unix Socket Permissions (PHP-FPM)

Wrong socket owner or SELinux context blocks fastcgi. Compare pool user with Nginx user.

fastcgi socket
permissions

PHP-FPM Pool Exhaustion

When pm.max_children is hit, new requests fail — often seen as 502/504.

TipWatch slow log and database queries before only raising children.
PHP-FPM
max_children

Verify the Fix

Test locally and through the public vhost.

bashtest
curl -sI http://127.0.0.1/
curl -sI https://your-domain/
verify
curl reload

Quick Reference

  • 502 → upstream not responding; check ss -tlnp
  • Read /var/log/nginx/error.log at the incident time
  • PHP: pool limits and socket path

Related tutorials

Diagrams are original illustrations by Gnome IT Solutions. Tutorial text © Gnome IT Solutions.