Solution:
Root Cause: Upstream Gateway Timeouts (HTTP 504) or Application Socket Exhaustion (HTTP 502) Web server access logs record every client connection, but standard access logging omits upstream processing times. When web servers fail to communicate with backend application sockets (e.g., PHP-FPM, Gunicorn, Node.js), they throw HTTP 502 Bad Gateway or HTTP 504 Gateway Timeout errors.
Step-by-Step Fix: 1 Isolate HTTP 5xx Status Code Frequency using awk:
Run an awk pipeline to calculate top occurring non-200 HTTP response codes in Nginx/Apache access logs: Copy
bash
awk '{print $9}' /var/log/nginx/access.log | sort | uniq -c | sort -rn | head -n 10
2 Correlate Specific 5xx Errors with Client Requests:
Filter out HTTP 502 and 504 errors along with destination URIs: Copy
bash
awk '$9 ~ /50[24]/ {print $4, $7, $9, $10}' /var/log/nginx/access.log | tail -n 50
3 Inspect Upstream Error Logs for Socket / Connection Refused Errors:
Check /var/log/nginx/error.log for exact backend failure messages: Copy
bash
sudo tail -f -n 100 /var/log/nginx/error.log | grep -E "connect\(\) failed|upstream timed out"
4 Enable High-Resolution Timing Attributes in Access Log Format:
Add upstream timing variables to /etc/nginx/nginx.conf under log_format: Copy
text
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'request_time=$request_time upstream_response_time=$upstream_response_time';