Applies to: Nginx, Apache or LiteSpeed in front of PHP-FPM, Node.js, Docker or another backend; error messages tested with Nginx 1.31.6
502 Bad Gateway means that a server acting as a gateway or proxy (Nginx, a load balancer or Cloudflare) asked the server behind it for the page and got no valid answer. The visitor’s browser is almost never the cause: the problem is the backend, such as PHP-FPM, a Node.js app or a container.
1. Find which layer shows the error
- A Cloudflare error page means Cloudflare could not get a valid response from your server. Check your server next.
- A plain page with
502 Bad Gatewayandnginxunderneath comes from Nginx on your server.
To test your server directly, bypassing Cloudflare (use your server’s IP address):
curl -sI --resolve example.com:443:203.0.113.10 https://example.com/ | head -1
2. Read the error log
sudo tail -n 50 /var/log/nginx/error.log
These are the messages we reproduced and what they mean:
connect() failed (111: Connection refused) while connecting to upstream: nothing listens on that port. The backend is stopped, or the port inproxy_passis wrong.connect() to unix:/run/php/php8.3-fpm.sock failed (2: No such file or directory): PHP-FPM is stopped, or the socket path infastcgi_passdoesn’t match (common after changing the PHP version).upstream prematurely closed connection while reading response header from upstream: the backend accepted the request but died before answering, often a crash, a fatal error or the out-of-memory killer.
3. Fix the backend
- Is it running?
sudo systemctl status php8.3-fpm # Ubuntu, Debian (php-fpm on AlmaLinux, Rocky Linux) sudo systemctl restart php8.3-fpm sudo docker ps # for containers; then: sudo docker logs <name>
- Does the address match? Compare
ls /run/php/(or the app’s port, see which process uses a port) with thefastcgi_passorproxy_passline, then runsudo nginx -t && sudo systemctl reload nginx. - Is memory running out?
sudo journalctl -k | grep -i "killed process"shows processes stopped by the out-of-memory killer. Add RAM, lower PHP-FPM’spm.max_childrenor fix the memory-hungry script. - Is PHP-FPM full? The PHP-FPM log says
server reached pm.max_children setting. Raise it only if the server has enough RAM.
cPanel servers
With Nginx in front of Apache: fix an Engintron 502 Bad Gateway and Nginx 502 and a missing error log.
A backend that answers too slowly gives a different error, 504. If your server keeps running out of resources, compare our KVM VPS plans or ask an engineer.
