Nginx 502 Bad Gateway means Nginx cannot connect to the upstream backend — usually PHP-FPM or a proxied application. This guide covers every cause systematically.
Step 1 — Check Nginx Error Log
sudo tail -50 /var/log/nginx/error.log
# Look for: "connect() failed", "no live upstreams", "upstream timed out"
Step 2 — Check PHP-FPM is Running
sudo systemctl status php8.2-fpm
sudo systemctl restart php8.2-fpm
# Check PHP-FPM error log
sudo tail -30 /var/log/php8.2-fpm.log
Step 3 — Verify Socket/Port Match
# Check Nginx config
grep "fastcgi_pass" /etc/nginx/sites-available/yoursite
# Check PHP-FPM pool config
grep "listen" /etc/php/8.2/fpm/pool.d/www.conf
# Both must match — either:
# fastcgi_pass unix:/run/php/php8.2-fpm.sock;
# listen = /run/php/php8.2-fpm.sock
# OR:
# fastcgi_pass 127.0.0.1:9000;
# listen = 127.0.0.1:9000
Step 4 — Fix Socket Permissions
# Check socket exists
ls -la /run/php/php8.2-fpm.sock
# Fix permissions in pool config
sudo nano /etc/php/8.2/fpm/pool.d/www.conf
listen.owner = www-data
listen.group = www-data
listen.mode = 0660
sudo systemctl restart php8.2-fpm
Step 5 — Fix PHP-FPM Worker Exhaustion
# Check if all workers are busy
sudo php-fpm8.2 -t
sudo cat /var/log/php8.2-fpm.log | grep "reached pm.max_children"
# If yes — increase workers in pool config
pm.max_children = 50
pm.start_servers = 10
pm.min_spare_servers = 5
pm.max_spare_servers = 20
Step 6 — Fix Upstream Timeout
# In Nginx site config — increase timeouts
fastcgi_connect_timeout 300;
fastcgi_send_timeout 300;
fastcgi_read_timeout 300;
Conclusion
502 errors are almost always PHP-FPM related. Our team resolves server errors with 15-minute emergency response.
Comments