Back to BlogWeb Hosting

Resolving 502 Bad Gateway Errors on Nginx Reverse Proxy: A Step‑by‑Step Guide

Learn how to diagnose and fix 502 Bad Gateway errors in Nginx reverse proxy setups with practical commands and config tweaks.

O
One MegaByte Team
January 5, 2026
4 min read
Resolving 502 Bad Gateway Errors on Nginx Reverse Proxy: A Step‑by‑Step Guide

Introduction

A 502 Bad Gateway response is one of the most frustrating HTTP errors you can encounter on a production web server. It tells visitors (and you) that the gateway or proxy – in most modern stacks, Nginx – received an invalid response from an upstream server. While the message is short, the root causes are many: mis‑configured upstream blocks, timeout mismatches, exhausted resources, or even subtle DNS hiccups.

In this article, One MegaByte walks you through a systematic troubleshooting process that pinpoints the exact failure point and provides concrete configuration fixes. By the end, you’ll be able to turn a 502 nightmare into a stable, high‑performance reverse‑proxy environment.


Why 502 Happens – The Most Common Culprits

CategoryTypical SymptomQuick Check
Upstream service downNginx logs connect() failed (111: Connection refused)curl http://127.0.0.1:8080/health
Timeouts too lowLogs show upstream timed out (110: Connection timed out)Compare proxy_read_timeout vs. app response time
Incorrect upstream addressDNS resolution errors, no resolver defineddig upstream.example.com
Resource exhaustionHigh CPU/Memory, worker_connections limit reachedtop, free -m
Header size overflowclient header buffer size is too smallCheck large_client_header_buffers

Understanding which bucket you fall into saves hours of blind trial‑and‑error.


Prerequisites

  • Access to the Nginx server (root or sudo)
  • Ability to view logs (/var/log/nginx/error.log and access.log)
  • Basic knowledge of the upstream application (e.g., Node.js, PHP‑FPM, Gunicorn)
  • curl and netcat (nc) installed on the host

Step 1 – Verify the Upstream Service Is Healthy

The first thing to confirm is that the service Nginx proxies to is actually running and responding.

# Replace with your upstream host/port
UPSTREAM_HOST=127.0.0.1
UPSTREAM_PORT=8080

# Simple TCP check
nc -zvw3 $UPSTREAM_HOST $UPSTREAM_PORT && echo "Port open" || echo "Port closed"

# HTTP health‑check (adjust path if needed)
curl -s -o /dev/null -w "%{http_code}\n" http://$UPSTREAM_HOST:$UPSTREAM_PORT/health

If the port is closed or the health endpoint returns anything other than 200, restart the upstream service and inspect its own logs.


Step 2 – Inspect Nginx Error Logs for the Exact Failure

Nginx provides granular error messages that point directly to the problem.

# Tail the last 100 lines and filter for 502
tail -n 100 /var/log/nginx/error.log | grep "502"

Typical entries you might see:

  • connect() failed (111: Connection refused) while connecting to upstream – upstream not listening.
  • upstream timed out (110: Connection timed out) while reading response header from upstream – timeout too low.
  • no resolver defined to resolve upstream – DNS issue.

Copy the exact phrase; it will guide the next configuration tweak.


Step 3 – Align Nginx Proxy Timeouts with Application Response Times

A common cause is a mismatch between how long the backend needs to generate a response and the timeout Nginx is willing to wait.

# /etc/nginx/conf.d/app.conf (example snippet)
server {
    listen 80;
    server_name example.com;

    location / {
        proxy_pass http://app_backend;
        # Default is 60s – increase if your app needs more time
        proxy_connect_timeout 30s;
        proxy_send_timeout    60s;
        proxy_read_timeout    120s;   # <-- adjust this value
        send_timeout          60s;
    }
}

upstream app_backend {
    server 127.0.0.1:8080;
    keepalive 16;
}

After editing, test the configuration and reload:

nginx -t && systemctl reload nginx

If the upstream still takes longer, increase proxy_read_timeout until the request succeeds.


Step 4 – Fix DNS‑Related 502 Errors

When you use a domain name in the upstream block (e.g., server api.internal:5000;), Nginx resolves it once at startup. If the DNS entry changes or the resolver cannot be reached, you’ll see errors like:

no resolver defined to resolve api.internal

Add a resolver directive that points to a reliable DNS server (Google’s 8.8.8.8 is a safe default):

resolver 8.8.8.8 8.8.4.4 valid=300s;

upstream api_backend {
    server api.internal:5000 resolve;   # "resolve" forces re‑lookup on each request
}

The valid parameter controls how long the cached record lives. Reload Nginx after the change.


Step 5 – Tune Worker Connections and Buffer Sizes

If your site experiences spikes, Nginx may run out of worker connections, leading to 502 responses even when the upstream is healthy.

# /etc/nginx/nginx.conf (global settings)
worker_processes auto;
events {
    worker_connections 4096;   # increase from default 1024
    multi_accept on;
}

# Optional: increase header buffers for large cookies or JWTs
http {
    large_client_header_buffers 4 16k;
}

Again, test and reload. Monitor the worker_connections metric with nginx_status or netstat -anp | grep :80.


Step 6 – Verify System Resources Are Sufficient

A starving server can cause Nginx to drop connections, which surface as 502 errors.

# CPU & memory
top -b -n1 | head -n 15

# Open file descriptors (Nginx needs many)
ulimit -n   # should be >= 4096 for high‑traffic sites

If limits are low, raise them in /etc/security/limits.conf:

*               soft    nofile          65535
*               hard    nofile          65535

After editing, log out and back in or restart the service.


Step 7 – Test the Fixes End‑to‑End

Use curl with verbose output to see the full request/response cycle:

curl -v https://example.com/api/status

A successful run should end with HTTP/1.1 200 OK and no 502 lines in the Nginx error log.

For a more realistic load test, run a short ab (ApacheBench) or hey command:

hey -n 200 -c 20 https://example.com/

Watch the Nginx error log in parallel to ensure no new 502 entries appear.


Conclusion

A 502 Bad Gateway error on an Nginx reverse proxy is rarely a mystery; it’s usually a misaligned expectation between Nginx and the upstream service. By following the systematic approach above—checking upstream health, reading precise log messages, adjusting timeouts, fixing DNS resolution, scaling worker connections, and confirming system resources—you can eliminate the majority of 502 incidents.

Implement these checks as part of your regular deployment checklist, and consider adding automated health‑checks (e.g., Prometheus alerts) to catch upstream failures before they affect users.

One MegaByte is ready to help you design resilient hosting architectures, whether you’re on bare‑metal, VPS, or managed cloud platforms. Reach out for a deep‑dive performance audit or a custom Nginx tuning service.


Keywords: 502 Bad Gateway, Nginx reverse proxy, timeout configuration, upstream health check, DNS resolver, worker connections, web hosting troubleshooting

Web HostingProblem SolvingTutorial