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. 1.Upstream slow - Backend processing too long
  2. 2.Proxy timeout too short - Default 60s insufficient
  3. 3.Backend overloaded - Cannot handle requests
  4. 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

nginx
# 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

bash
# Check backend performance:
# - Optimize queries
# - Add caching
# - Scale horizontally

Nginx 504 Checklist

CheckSettingExpected
proxy_read_timeoutconfigAdequate
Backend responsecurl testFast enough
Backend healthhealth checkHealthy

Verify the Fix

bash
curl -I http://example.com/api/
# Output: HTTP/1.1 200 OK
  • [Fix Nginx 502 Bad Gateway](/articles/fix-502-bad-gateway)
  • [Fix Nginx Upstream Not Found](/articles/fix-nginx-upstream-not-found)