Skip to main content
nginxintermediatenetworkingVerified

Nginx 502 Bad Gateway: Causes and Fixes

Last reviewed: 9/14/2026
3 solutions

Exact Error Message

502 Bad Gateway

Quick Fix

Check if upstream server is running and accessible: curl http://upstream-server:port

What This Error Means

A 502 Bad Gateway error occurs when Nginx acts as a reverse proxy and cannot receive a valid response from the upstream server. This typically means the upstream server is down, misconfigured, or refusing connections.

Common Symptoms
  • Users see 502 Bad Gateway error
  • Nginx error logs show upstream connection failures
  • Partial or complete site outage
  • Intermittent connection failures
Common Causes
  • Upstream server is down or crashed
  • Upstream server is not listening on expected port
  • Firewall blocking connection to upstream
  • Upstream server overloaded or slow
  • DNS resolution issues
  • Nginx misconfiguration
Diagnostic Steps
  1. 1Check Nginx error logs: tail -f /var/log/nginx/error.log
  2. 2Test upstream server connectivity directly
  3. 3Check upstream server status and logs
  4. 4Verify firewall rules
  5. 5Check DNS resolution
  6. 6Review Nginx configuration

Solutions

Solution 1: Start or restart upstream server
  1. 1Check if upstream service is running
  2. 2Start the service if stopped
  3. 3Restart if service is in bad state
  4. 4Verify service is listening on correct port

Commands to Run

Restarting production services may cause brief downtime

sudo systemctl status SERVICE_NAME
sudo systemctl restart SERVICE_NAME
sudo netstat -tlnp | grep PORT
Solution 2: Fix firewall rules
  1. 1Check firewall status
  2. 2Allow connections from Nginx to upstream
  3. 3Verify security group rules (AWS)
  4. 4Test connectivity after changes

Commands to Run

Firewall changes affect system security

sudo ufw status
sudo ufw allow from NGINX_IP to any port PORT
sudo iptables -L
Solution 3: Fix Nginx configuration
  1. 1Review upstream server configuration
  2. 2Check proxy_pass directive
  3. 3Verify server names and ports
  4. 4Test configuration: nginx -t
  5. 5Reload Nginx: nginx -s reload

Commands to Run

Invalid Nginx configuration will prevent reload

nginx -t
sudo nginx -s reload
Prevention Tips
  • Implement health checks for upstream servers
  • Use load balancing with multiple upstreams
  • Monitor upstream server health
  • Set appropriate proxy timeouts
  • Implement graceful degradation

Version Notes: Applies to Nginx 1.18+

Was this helpful?