P2
504 Gateway Timeout — Nginx Troubleshooting Guide
Diagnose and fix Nginx 504 timeout errors caused by slow backend responses. Covers response time measurement, backend diagnostics, timeout tuning, and database query analysis.
15 min6 steps
Progress: 0/6 steps
0%
Find timeout-related errors.
tail -30 /var/log/nginx/error.log | grep -i 'timed out\|504\|upstream'
Expected: Common: 'upstream timed out (110: Connection timed out) while reading response header'. This means the backend took too long.
Measure how long the backend takes to respond directly.
time curl -s -o /dev/null -w '%{http_code} %{time_total}s' http://127.0.0.1:BACKEND_PORT/Expected: Response time in seconds. If it's over 60s, the backend itself is too slow.
Look at backend logs for slow queries, resource exhaustion, or errors.
journalctl -u BACKEND_SERVICE --since '10 minutes ago' --no-pager | tail -30
Expected: Look for slow database queries, connection pool exhaustion, or memory issues.
Increase proxy timeout values to allow more time for the backend.
# Add to nginx server or location block: proxy_connect_timeout 120; proxy_send_timeout 120; proxy_read_timeout 120; send_timeout 120;
Expected: After adding to config and reloading: nginx -t && systemctl reload nginx
This is a band-aid. The real fix is to make the backend respond faster. Long timeouts tie up Nginx worker connections.
Verify the backend server isn't resource-starved.
top -b -n 1 | head -20 && echo '---' && free -h
Expected: High CPU, low memory, or high I/O wait can all cause slow backend responses.
Slow database queries are the #1 cause of 504 errors.
# For PostgreSQL: SELECT pid, now() - pg_stat_activity.query_start AS duration, query FROM pg_stat_activity WHERE (now() - pg_stat_activity.query_start) > interval '5 seconds';
Expected: Any query running longer than 5 seconds may be causing the timeout.