A 502 Bad Gateway or 504 Gateway Timeout usually means Nginx could not obtain a valid response from the upstream application. The status code is a clue, not a complete diagnosis. Start by separating network connectivity, application health and proxy configuration.
Confirm the upstream is listening
Check the application service status and inspect its logs before changing Nginx settings. Verify the process is bound to the expected address and port. If the application uses a Unix socket, confirm that the socket exists and that the Nginx worker user has permission to connect to it.
Test from the proxy host
Run a local request from the server where Nginx runs, targeting the exact upstream address configured in proxy_pass. This distinguishes an application failure from a proxy routing issue. For containerized services, confirm that Nginx and the upstream share the correct network and that the service name resolves from the proxy container.
Read the error log
Nginx error messages often identify connection refused, no live upstreams, host not found or upstream timed out. Match the timestamp to the application log and system journal. A connection-refused error generally points to a listener or address mismatch; a timeout may indicate slow processing, saturation or a blocked network path.
Review timeouts instead of blindly increasing them
Proxy connect, send and read timeouts serve different purposes. Increase them only when the application legitimately needs more time, such as a long-running report or upload. For slow endpoints, consider background jobs and polling rather than keeping an HTTP connection open indefinitely.
Check headers and request size
Confirm that the proxy forwards the expected Host and client IP headers. Large uploads may require a higher client_max_body_size, while buffering behavior can affect streaming applications. Change one setting at a time and validate the configuration with nginx -t before reloading.
Use a repeatable incident workflow
Capture the request ID, timestamp, upstream target, response time and relevant log lines. Test a known healthy endpoint, compare a failing route and inspect CPU, memory and connection saturation. After the fix, run a synthetic request and watch error rates for recurrence.
Key lesson: a proxy error is often a symptom of an unhealthy or unreachable upstream. Verify the application and network path first, then adjust proxy configuration based on evidence.
Documentation: Nginx reverse proxy guide — https://nginx.org/en/docs/http/ngx_http_proxy_module.html
Read the exact upstream error before editing configuration
Nginx error messages often contain the most useful clue: connection refused, no live upstreams, host not found, permission denied or upstream timed out. Match the message to the request timestamp and inspect the application service log at the same time. A 502 response often indicates that Nginx could not establish or interpret a valid upstream response, while a 504 usually indicates that the upstream did not respond within the configured time. These codes are not proof of one specific cause. Avoid changing multiple proxy directives before confirming which layer is failing.
Verify address, port and network namespace
Check that the application listens on the address and port Nginx expects. A process bound only to 127.0.0.1 inside one container may not be reachable from a separate proxy container. In Docker networks, use the service DNS name and the container’s listening port rather than a host-only address. On a host installation, inspect listening sockets and local firewall rules. Test connectivity from the same network namespace as the Nginx worker where possible. A successful curl from your laptop does not prove that the proxy host can reach the backend.
Check Unix socket permissions
PHP-FPM and other local services may communicate through Unix domain sockets. Confirm that the configured socket path matches the service pool configuration and that the Nginx worker user has permission to connect. Directory traversal permissions matter as well as the socket’s own mode. After a service restart, verify that the socket is recreated with the expected owner and group. Avoid solving a permission problem by making the socket world-writable; use a dedicated group and a narrowly scoped permission model.
Distinguish slow application work from proxy timeout
Increasing proxy_read_timeout may hide an overloaded backend rather than fix it. Check application traces, database query time, external API calls and worker saturation for the slow request. A report export or long-running task may be better implemented as a background job that returns a job identifier and lets the client poll for completion. For normal web requests, set connect, send and read timeouts according to expected behavior. Record upstream response time so a rising latency trend is visible before users begin receiving gateway errors.
Review headers, body size and streaming behavior
Reverse proxies must forward the headers that the application relies on, including the original host and client address where appropriate. Configure trusted proxy handling in the application so forwarded headers cannot be spoofed by arbitrary clients. Large file uploads may require a suitable client_max_body_size and buffering strategy. Streaming responses and server-sent events may need different buffering and timeout behavior from ordinary pages. Make changes for the specific endpoint rather than weakening limits globally for every virtual host.
Validate DNS and upstream health
If the upstream is referenced by a hostname, confirm that it resolves from the Nginx environment and that DNS changes are handled as expected. Container service names may change when deployments are recreated, and long-lived DNS resolution can leave a proxy pointing at an old address depending on configuration. For multiple upstream servers, inspect health checks and failure thresholds. A pool can report no live upstreams even though one backend is healthy if the configured targets or health assumptions are wrong.
Use a safe configuration change process
Back up the current virtual-host configuration, make one targeted change and run nginx -t before reloading. Prefer a graceful reload to a hard restart so active connections can complete. Keep a rollback copy and verify both the failing route and a known-good route afterward. If the change affects TLS, host routing or upload limits, test those paths explicitly. Avoid copying a complete configuration from a different server because module versions, upstream topology and security requirements may differ.
Build an incident record that speeds future diagnosis
Capture the request path, timestamp, response code, upstream address, connect time, response time and relevant log lines. Note whether the issue affects all requests or only one route, one tenant or one backend node. After resolution, add the root cause and preventive action to the runbook. Repeated 502 or 504 errors may point to capacity planning, deployment sequencing or dependency reliability rather than a one-off Nginx setting. Use synthetic checks to detect the failure before customers report it.





