What's Actually Happening
Nginx returns 504 Gateway Timeout error when upstream server takes too long to respond.
The Error You'll See
```bash $ curl http://example.com/api/slow
<html> <head><title>504 Gateway Time-out</title></head> <body> <center><h1>504 Gateway Time-out</h1></center> </body> </html> ```
Why This Happens
- 1.Upstream slow - Backend processing too long
- 2.Proxy timeout too short - Default 60s insufficient
- 3.Backend overloaded - Cannot handle requests
- 4.Network latency - Slow connection to upstream
Step 1: Check Error Logs
```bash # Nginx error log: tail -f /var/log/nginx/error.log
# Look for: upstream timed out (110: Connection timed out) while reading response header from upstream ```
Step 2: Increase Timeout
# In nginx.conf:
location /api/ {
proxy_pass http://backend;
proxy_connect_timeout 300s;
proxy_send_timeout 300s;
proxy_read_timeout 300s;
}Step 3: Check Upstream
```bash # Test backend directly: curl -v http://backend:8080/api/slow
# Check backend health: curl http://backend:8080/health ```
Step 4: Optimize Backend
# Check backend performance:
# - Optimize queries
# - Add caching
# - Scale horizontallyNginx 504 Checklist
| Check | Setting | Expected |
|---|---|---|
| proxy_read_timeout | config | Adequate |
| Backend response | curl test | Fast enough |
| Backend health | health check | Healthy |
Verify the Fix
curl -I http://example.com/api/
# Output: HTTP/1.1 200 OKRelated Issues
- [Fix Nginx 502 Bad Gateway](/articles/fix-502-bad-gateway)
- [Fix Nginx Upstream Not Found](/articles/fix-nginx-upstream-not-found)