DEV Community

Daniele Michelin
Daniele Michelin

Posted on Originally published at daniele-michelin.com

HTTP 502 Bad Gateway (nginx, PHP-FPM): how to fix

nginx could not get a valid response from the upstream (PHP-FPM, Node.js, Gunicorn, a Docker container) – the backend is down, unreachable or crashed.

Common causes

  • PHP-FPM is stopped or crashed (e.g. after an update or an OOM kill).
  • The socket path no longer matches after a PHP upgrade, e.g. php8.2-fpm.sock instead of php8.3-fpm.sock.
  • No permission on the socket: listen.owner/listen.group do not match the nginx user.
  • The backend listens on a different port or only on IPv6/IPv4.
  • The PHP worker dies mid-request (segfault): upstream prematurely closed connection.

How to check it

Read the latest errors in the nginx log

tail -n 50 /var/log/nginx/error.log
Enter fullscreen mode Exit fullscreen mode

Check PHP-FPM status

systemctl status php8.3-fpm
Enter fullscreen mode Exit fullscreen mode

Does the socket exist and who owns it?

ls -l /run/php/
Enter fullscreen mode Exit fullscreen mode

What actually helps

  1. Restart PHP-FPM or the backend with systemctl restart php8.3-fpm, then look for the root cause in the journal.
  2. Point fastcgi_pass to the correct socket, then nginx -t && systemctl reload nginx.
  3. Set listen.owner = www-data and listen.group = www-data in the FPM pool.

FAQ

What is the difference between 502 and 504?

502: the backend does not answer at all or answers garbage. 504: the backend is reachable but takes longer than the nginx timeout.

Why does 502 only happen occasionally?

Typical for crashing workers or a full listen backlog. Look for SIGSEGV or OOM messages in the journal and Resource temporarily unavailable in the nginx log.


Full page with every command and the German/Italian version: daniele-michelin.com/en/errors/http-502-bad-gateway/

First published at daniele-michelin.com. The error lexicon covers HTTP, DNS, TLS, mail, database, PHP, nginx, systemd and Nextcloud, in German, English and Italian.

Top comments (0)