mobile wallpaper 1mobile wallpaper 2mobile wallpaper 3mobile wallpaper 4
270 words
1 minute
Nginx 502/504 Troubleshooting Guide: Locating and Fixing Common Reverse Proxy Failures
2025-06-28

502 Bad Gateway and 504 Gateway Timeout are the most common failures in reverse proxy scenarios. Many people just restart the service directly, but without locating the root cause, the problem will repeatedly occur.

1. Distinguish Between 502 and 504 First#

  • 502: Nginx can contact the upstream, but the upstream returns an anomaly or the connection fails.
  • 504: Nginx waits for the upstream and times out.

This distinction will determine the direction of your troubleshooting.

2. The First Scene: Check the Logs#

sudo tail -n 200 /var/log/nginx/error.log
sudo tail -n 200 /var/log/nginx/access.log

Focus on:

  • connect() failed
  • upstream timed out
  • no live upstreams

3. Verify if the Upstream Service is Alive#

curl -I http://127.0.0.1:8080
ss -tulpen | rg 8080

If you can’t even access the upstream locally, fix the upstream application first; don’t modify Nginx right away.

4. Check the Proxy Configuration#

Common issues:

  • proxy_pass address is wrong.
  • Upstream port changed but wasn’t synced.
  • Missing Host header causing upstream routing to fail.

Reference:

location / {
proxy_pass http://127.0.0.1:8080;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_connect_timeout 5s;
proxy_read_timeout 60s;
}

5. Troubleshooting Resource Bottlenecks#

If the failure is sporadic, focus on resources:

top
free -m
df -h

High-frequency root causes:

  • Insufficient memory causing the upstream process to be killed by OOM.
  • CPU maxed out causing response timeouts.
  • Disk full causing log or temporary file writes to fail.

6. Docker Scenario Supplement#

If Nginx and the upstream are in Docker:

  • Check if the containers are in the same network.
  • proxy_pass should point to the service name, not localhost.
  • Is the container restart policy reasonable?

7. Verification After Fixing#

  1. nginx -t to check if the configuration is valid.
  2. Smooth reload: systemctl reload nginx.
  3. Continuously stress test / access for 5-10 minutes to observe if it recurs.

Summary#

The key to 502/504 is not “restarting fixed it”, but establishing a stable troubleshooting sequence: Logs -> Upstream -> Configuration -> Resources. Once the process is fixed, the failure recovery time will be significantly shortened.

Share

If this article helped you, please share it with others!

Nginx 502/504 Troubleshooting Guide: Locating and Fixing Common Reverse Proxy Failures
https://blog.levifree.com/posts/nginx-502-504-troubleshooting/
Author
LeviFREE
Published at
2025-06-28
License
CC BY-NC-SA 4.0

Some information may be outdated

Table of Contents