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.logsudo tail -n 200 /var/log/nginx/access.logFocus on:
connect() failedupstream timed outno live upstreams
3. Verify if the Upstream Service is Alive
curl -I http://127.0.0.1:8080ss -tulpen | rg 8080If 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_passaddress is wrong.- Upstream port changed but wasn’t synced.
- Missing
Hostheader 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:
topfree -mdf -hHigh-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_passshould point to the service name, notlocalhost.- Is the container restart policy reasonable?
7. Verification After Fixing
nginx -tto check if the configuration is valid.- Smooth reload:
systemctl reload nginx. - 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.
If this article helped you, please share it with others!
Some information may be outdated





