How to Fix Nginx 502
Quick Fix Summary
TL;DRCheck if your upstream service (e.g., PHP-FPM, Node.js, or another backend) is running and accessible on its configured port.
Nginx returns a 502 Bad Gateway error when it cannot successfully communicate with an upstream server it's configured to proxy requests to. This indicates a failure in the backend service, not Nginx itself.
Diagnosis & Causes
Recovery Steps
Step 1: Verify Upstream Service Status
First, confirm the backend application or process manager is actively running and listening on the expected port.
# Check if PHP-FPM is running
sudo systemctl status php8.1-fpm
# Check if a Node.js/Go app is listening on port 3000
sudo ss -tlnp | grep :3000
# Check for Gunicorn/Uvicorn processes
ps aux | grep -E '(gunicorn|uvicorn)' Step 2: Test Network Connectivity to Upstream
Rule out basic network issues by testing the connection from the Nginx server to the upstream server's IP and port.
# Test if the port is open (replace 9000 with your backend port)
nc -zv 127.0.0.1 9000
# Use curl with a timeout to simulate a request
curl -I --max-time 5 http://localhost:3000/health Step 3: Analyze Nginx & Upstream Logs
Check error logs for specific connection failures, timeouts, or permission denied messages. Tail logs in real-time.
# Check Nginx error log (common paths)
sudo tail -f /var/log/nginx/error.log
sudo journalctl -u nginx -f
# Check upstream service logs (e.g., PHP-FPM)
sudo tail -f /var/log/php8.1-fpm.log Step 4: Adjust Nginx Proxy Timeouts and Buffers
If the upstream is slow, increase Nginx's timeout and buffer settings to prevent premature 502 errors.
# Inside your location or server block in /etc/nginx/sites-available/your_site
location / {
proxy_pass http://backend;
proxy_connect_timeout 60s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
proxy_buffer_size 128k;
proxy_buffers 4 256k;
proxy_busy_buffers_size 256k;
}
# Test config and reload
sudo nginx -t && \
sudo systemctl reload nginx Architect's Pro Tip
"For PHP-FPM, a saturated `pm.max_children` pool is a silent killer. Check `pm.status` page; if all children are busy, new requests queue and timeout, causing 502s."
Frequently Asked Questions
I fixed the backend service, but 502 persists. What's wrong?
Nginx may have cached the bad upstream state. Restart Nginx to clear its connection pools: `sudo systemctl restart nginx`.
Can a 502 error be caused by DNS?
Yes. If `proxy_pass` uses a hostname that fails to resolve, Nginx cannot find the upstream. Use static IPs in production or ensure DNS is reliable.
My upstream is on a different server. What should I check first?
Check the firewall rules (`sudo ufw status`) on both servers and network security groups (AWS/Azure) to ensure the backend port is allowed from the Nginx server's IP.