How to fix 502 Bad Gateway

A 502 means the web server asked the program behind it for a page and got no usable answer. Find which part failed in five checks.

2–3 minutes
Tangled network cables in a rack

502 Bad Gateway means a server acting as a go-between, usually Nginx, a load balancer or a CDN, passed your request to the program behind it and got an invalid answer or none at all. The go-between is fine; the thing behind it is not.

If you are visiting the site

The problem is on the website’s side. Reload after a minute, since a 502 is often brief while a service restarts. If it persists, try again later, or check whether others report the site is down.

If you run the site

Work from the go-between backwards. Most 502s have one of these causes.

1. Is the backend running?

For PHP sites the backend is PHP-FPM; for apps it is the app’s own process.

systemctl status php8.3-fpm
systemctl status php-fpm

The first name is used on Ubuntu and Debian (your version number may differ), the second on RHEL-based systems. If it is stopped or failing, start it and read why it stopped:

sudo systemctl restart php8.3-fpm
sudo journalctl -u php8.3-fpm -n 50

2. Read the web server’s error log

The log says exactly what went wrong:

sudo tail -n 50 /var/log/nginx/error.log
Log saysMeaning
connect() to unix:/run/php/... failed (2: No such file or directory)The socket path in Nginx does not match PHP-FPM’s
connect() failed (111: Connection refused)Nothing listening on that port; app is down
connect() ... failed (13: Permission denied)Socket permissions, or SELinux blocking the connection
upstream prematurely closed connectionThe backend crashed while handling the request

3. Check the socket or port matches

Compare fastcgi_pass (or proxy_pass) in your Nginx site with the listen line in the PHP-FPM pool file, usually under /etc/php/8.3/fpm/pool.d/ or /etc/php-fpm.d/. They must point at the same socket or port.

4. Check memory

When a server runs out of memory, the kernel kills processes, and PHP or the app is often first.

free -h
sudo dmesg -T | grep -i 'killed process'

If you see killed processes, add memory, add swap, or lower PHP-FPM’s pm.max_children.

5. SELinux on RHEL-based systems

On AlmaLinux, Rocky and RHEL, Nginx may not connect to a network port until you allow it:

sudo setsebool -P httpd_can_network_connect 1

Behind a CDN or load balancer

If the 502 page is branded by your CDN, the CDN could not reach your server at all. Check the server is up, that its firewall allows the CDN, and that the CDN points at the right IP.

Something out of date? Software changes. If a step no longer works, tell us and we will check it and update the page.