Sub topic 14
Reading logs and troubleshooting 502, 504 and other upstream errors
This chapter assumes you can already write a proxy_pass configuration, define an upstream group, and run nginx -t and reload. It also assumes you can read an HTTP status code. Here you will learn to find out why a proxied request failed, using the access log, the error log and a few shell commands.
Where Nginx logs and what each log is for
On a distribution package, Nginx writes two logs by default:
/var/log/nginx/access.loghas one line per finished request. It tells you what status the client received and how long it took./var/log/nginx/error.loghas diagnostic messages from Nginx itself, such as failed connections and timeouts. It tells you why a request failed.
Start with the access log to find which requests fail. Then use the timestamp to find the matching entry in the error log. Useful commands:
sudo tail -f /var/log/nginx/error.log
sudo grep -E ' (502|504) ' /var/log/nginx/access.log | tail -n 20
sudo journalctl -u nginx --since "10 minutes ago"The error_log directive sets the file and the minimum severity (error_log /var/log/nginx/error.log warn;). The default level is error. That level is enough for the messages in this chapter.
Logging upstream details
The default combined format does not say which backend served a request. Define a format that does. This is the custom format from the plan. It goes in the http context, and the access_log line can go there or in a server or location block:
log_format upstream_log '$remote_addr [$time_local] "$request" $status '
'upstream=$upstream_addr '
'upstream_status=$upstream_status '
'urt=$upstream_response_time rt=$request_time';
access_log /var/log/nginx/proxy_access.log upstream_log;| Variable | Meaning |
|---|---|
| `$status` | Status Nginx sent to the client |
| `$upstream_addr` | Address of the backend that was tried |
| `$upstream_status` | Status the backend returned |
| `$upstream_response_time` | Seconds the backend took, from connect to the end of its response |
| `$request_time` | Seconds from the first byte of the request to the last byte sent to the client |
A typical failing line looks like this:
203.0.113.5 [28/Nov/2026:03:50:12 +0000] "GET /api/items HTTP/1.1" 504 upstream=10.0.0.11:8080 upstream_status=504 urt=60.001 rt=60.001The 60 seconds match the default proxy_read_timeout, so the backend accepted the connection but did not answer in time.
Reading retries
When Nginx retries a request on another server, the upstream variables hold comma-separated lists, one entry per attempt:
"GET /api/items HTTP/1.1" 200 upstream=10.0.0.11:8080, 10.0.0.12:8080 upstream_status=502, 200 urt=0.001, 0.045 rt=0.046The first backend failed with 502 after 1 ms. The second returned 200. The client saw only the 200. A group of backends is often failing quietly, and lines like this show it. Search for them regularly:
sudo grep -E 'upstream_status=[0-9]+, ' /var/log/nginx/proxy_access.log | tailIf $upstream_status is -, no backend produced a status. Nginx either never connected or answered from its own logic, for example a cache hit or a redirect.
What the status codes mean
| Status | Typical cause |
|---|---|
| 502 Bad Gateway | The backend refused the connection, closed it early, sent an invalid response, or every server in the group is marked unavailable |
| 503 Service Unavailable | Usually the backend itself, or Nginx rate limiting (`limit_req`, `limit_conn`). A dead upstream group gives 502, not 503 |
| 504 Gateway Timeout | Nginx connected but the backend did not connect, answer or send data within a timeout |
| 499 | Nginx-specific. The client closed the connection before Nginx replied, which is often a client timeout or a user navigating away |
| 413 | Request body larger than `client_max_body_size` (default 1 MB), rejected before reaching the backend |
| 404 from the backend | Often a `proxy_pass` URI mistake, because the backend received a different path than you intended |
Matching error log messages to causes
The error log line names the failure and the phase it happened in. Read the text after the error code and the phrase starting with "while".
| Error log message | Status | Meaning and first check |
|---|---|---|
| `connect() failed (111: Connection refused) while connecting to upstream` | 502 | Nothing listens on that address and port. Is the app running, and on which port? |
| `connect() failed (13: Permission denied) while connecting to upstream` | 502 | Usually SELinux blocking Nginx from making network connections |
| `upstream timed out (110: Connection timed out) while connecting to upstream` | 504 | Packets are dropped, typically by a firewall or a wrong IP address |
| `upstream timed out (110: Connection timed out) while reading response header from upstream` | 504 | The app is accepting connections but responding too slowly |
| `upstream prematurely closed connection while reading response header from upstream` | 502 | The app crashed or closed the socket mid-request |
| `recv() failed (104: Connection reset by peer) while reading response header from upstream` | 502 | The backend reset the connection, which is often a crash or a protocol mismatch such as plain HTTP sent to a TLS port |
| `no live upstreams while connecting to upstream` | 502 | Every server in the group is marked failed for the current `fail_timeout` |
| `upstream sent too big header while reading response header from upstream` | 502 | Response headers (often large cookies) exceed `proxy_buffer_size` |
| `client intended to send too large body` | 413 | Raise `client_max_body_size` |
A diagnostic workflow
Work from the outside in. Skipping straight to timeout tuning hides real faults.
Run these checks on the proxy host:
# 1. Is anything listening on the backend port?
sudo ss -ltnp | grep ':8080'
# 2. Does the backend answer when you bypass Nginx?
curl -sS -o /dev/null -w '%{http_code} %{time_total}s\n' http://10.0.0.11:8080/
# 3. Does the same request work through Nginx?
curl -sS -o /dev/null -w '%{http_code} %{time_total}s\n' -H 'Host: example.com' http://127.0.0.1/If step 2 fails, the problem is the backend or the network, not Nginx. If step 2 works and step 3 fails, compare the error log with your proxy_pass, headers and timeouts. Remember that curl from the proxy host tests the path from that host. A firewall rule that only affects the proxy's address will not show up when you test from your laptop.
SELinux on RHEL-family systems
If the error log shows 13: Permission denied and the backend works with curl, check the audit log. Then allow Nginx to connect out:
sudo setsebool -P httpd_can_network_connect 1The -P flag makes the change persistent across reboots.
Fixing timeouts without hiding problems
Three timeouts matter for proxying, and each defaults to 60 seconds:
proxy_connect_timeoutis how long Nginx waits to establish the TCP connection. Leave it short, since a healthy backend on the same network connects in milliseconds.proxy_read_timeoutis the longest gap between two successive reads from the backend, not the total response time. Raise it only for endpoints that are legitimately slow, and scope it to a specificlocation.proxy_send_timeoutis the longest gap between two successive writes to the backend.
Retries are governed by proxy_next_upstream, which defaults to error timeout. A request is retried on the next server only if it can safely be repeated. By default, a non-idempotent request (such as POST) that has already been sent to a backend is not retried. If you add non_idempotent, a timed-out POST may run twice on the backend, so do that only when the application tolerates duplicates.
Retries can also mask an overloaded group. A long urt list with several entries means your users waited through multiple failures. Limit the damage with proxy_next_upstream_tries and proxy_next_upstream_timeout.
Debug logging
When the normal log does not explain a failure, raise the log level for a short time:
error_log /var/log/nginx/error.log debug;Debug output requires an Nginx binary built with --with-debug. Check with nginx -V 2>&1 | grep -o with-debug. Many distributions ship such a build, some as a separate package such as nginx-debug. Debug logs are very large and include request details. Use them briefly, ideally in a test environment, then revert and reload.
Common mistakes
- Reading only the status code. Both a dead app and a firewall drop cause a failure, but the first gives 502 and the second 504. The error log distinguishes them.
- Blaming Nginx for a slow app. If
urtis close tort, the time was spent in the backend. - Raising
proxy_read_timeoutglobally. This lets slow requests tie up workers and connections. Scope it to the affectedlocation. - Forgetting that the log file is empty. If the access log stays empty after a change, check the
access_logpath, directory permissions and whether log rotation reopened the file.
Exercise
Your access log shows 502 upstream=10.0.0.11:8080, 10.0.0.12:8080 upstream_status=502, 502 urt=0.001, 0.001, and the error log says connect() failed (111: Connection refused) for both addresses. What is wrong, which command would you run first, and why is the client seeing a 502 rather than a 504?
Show answer
Nothing is listening on port 8080 on either backend, so both connection attempts were refused immediately (about 1 ms each). Run sudo ss -ltnp | grep ':8080' on each backend, or curl the backend directly, to confirm the app is down or on a different port. The client sees 502 because Nginx received an immediate refusal, which it treats as a bad gateway. A 504 would appear only if the connection or response timed out.
Exercise
A report endpoint takes about 90 seconds and the access log shows 504 ... urt=60.001. Which setting would you change, where would you place it, and what is the risk of putting it in the http block?
Show answer
Set proxy_read_timeout 120s; in the location that serves the report endpoint, then test and reload. Placing it in the http block raises the limit for every location, so hung backends would hold connections and workers for longer on all other requests.