A 502 means your web server (nginx) reached the backend (PHP-FPM, an app server) but got an invalid or no response. The web server itself is fine — the thing behind it crashed, timed out, or is misconfigured. Here is how to fix it.
Quick answer
A 502 Bad Gateway means nginx works but got no valid response from the backend behind it. Most often PHP-FPM is down — restart it — or nginx points at the wrong socket or port, or the backend crashed or timed out. The nginx error log and the PHP-FPM log show which one.
Cause 1: PHP-FPM is down
The most common cause. If the PHP-FPM service crashed or isn't running, nginx has nothing to talk to. Restart it and check the logs:
systemctl status php-fpm # or php8.x-fpm
systemctl restart php-fpm
tail -50 /var/log/nginx/error.logCause 2: the backend timed out
A slow script (or a long DB query) that exceeds the proxy timeout returns a 502. The nginx error log shows "upstream timed out" or "prematurely closed". Fix the slow request, or raise the timeout if the work is legitimately long.
Cause 3: wrong socket / port
If nginx points to a PHP-FPM socket or port that doesn't match FPM's config, every request 502s. Make sure fastcgi_pass matches FPM's listen directive.
502 = the backend gave a bad/no response (often crashed). 504 = the backend took too long (a timeout). They point at different fixes — see our 504 guide.
The clean checklist
- Check the nginx error log — it names the real cause.
- Restart PHP-FPM (or your app backend) and confirm it's running.
- Look for a crashed backend (out of memory? see the OOM killer).
- Verify
fastcgi_passmatches FPM's listen socket/port.
502 = the backend failed. Restart PHP-FPM, read the nginx error log, and fix the crashed or mismatched backend.
Cause 4: the backend ran out of memory
If PHP-FPM workers (or your app process) get killed by the Linux out-of-memory killer, nginx immediately sees a dead connection and returns 502. Check dmesg/syslog for OOM kill messages — see the OOM killer guide. Fixing memory limits or the underlying leak stops the crash.
Cause 5: a bad deploy or fatal PHP error
A code deploy with a syntax error or a fatal error on every request crashes PHP-FPM workers repeatedly. Check the PHP-FPM error log — not just nginx's — for the actual fatal error, and roll back or fix the offending code.
How to prevent 502s
- Monitor PHP-FPM and auto-restart it on failure (a supervisor or systemd Restart=on-failure).
- Set realistic pm.max_children for your RAM so workers don't get OOM-killed.
- Test deploys on staging before production.
- Keep an eye on the error log so a bad release is caught in minutes, not hours.
Related errors
A 502 (bad/no response) is not the same as a 504 Gateway Timeout (too slow) or a 500 Internal Server Error (the app itself threw an error and still responded). If the database is the actual culprit, see MySQL/MariaDB won't start.