What Is 502 Bad Gateway?
A 502 error means your web server (Nginx) received an invalid response from an upstream server (typically PHP-FPM, Node.js, or another backend). The web server is working, but the backend is not responding correctly.
Common Causes and Fixes
1. PHP-FPM Is Not Running
systemctl status php8.2-fpm
# If not running:
sudo systemctl start php8.2-fpm2. PHP-FPM Socket Mismatch
# Check what Nginx expects
grep fastcgi_pass /etc/nginx/sites-enabled/*
# Check what PHP-FPM provides
grep "listen =" /etc/php/8.2/fpm/pool.d/www.conf
# They must match (both socket or both TCP)3. PHP-FPM Workers Exhausted
# Check active connections
sudo systemctl status php8.2-fpm
# Increase workers in /etc/php/8.2/fpm/pool.d/www.conf
pm = dynamic
pm.max_children = 50
pm.start_servers = 10
pm.min_spare_servers = 5
pm.max_spare_servers = 20
sudo systemctl restart php8.2-fpm4. Backend Application Crashed
# Node.js app
pm2 status
pm2 restart all
# Python/Gunicorn
systemctl status gunicorn
journalctl -u gunicorn --since "5 minutes ago"5. Upstream Timeout
# Increase timeout in Nginx
location ~ \.php$ {
fastcgi_read_timeout 300;
fastcgi_send_timeout 300;
...
}Diagnostic Steps
# 1. Check Nginx error log
tail -20 /var/log/nginx/error.log
# 2. Check PHP-FPM log
tail -20 /var/log/php8.2-fpm.log
# 3. Check if backend is listening
ss -tlnp | grep -E ":9000|php"