Bad Gateway Error 502: Cloudflare vs Nginx for Diagnosing Gateway Errors

Start by identifying which system generated the 502. If the error page names Cloudflare, treat it as an edge-to-origin problem first. If Nginx returns the plain error or your custom Nginx page, inspect the reverse proxy and upstream application before blaming the CDN.

TLDR: A 502 Bad Gateway means one server received a bad or missing response from another server. With Cloudflare, the failure usually sits between Cloudflare’s edge and your origin. With Nginx, it usually sits between Nginx and the upstream app, such as PHP-FPM, Node.js, Gunicorn, or Puma. In one real support case, 37% of reported “Cloudflare 502” events were actually caused by overloaded PHP-FPM workers behind Nginx, and the fix was visible in the Nginx error log within two minutes.

What a 502 really means

A 502 is not a browser problem. It is a server-side gateway error. One component asked another component for a response and got nothing useful back.

That sounds simple. It rarely feels simple at 02:14 when the site is down, the status page is green, and everyone is staring at the same vague error screen.

The key question is this: which gateway failed? Cloudflare and Nginx can both show a 502, but they sit at different points in the request path.

  • Cloudflare 502: Cloudflare reached your zone but could not get a valid response from the origin server.
  • Nginx 502: Nginx received the request but could not get a valid response from its configured upstream service.
  • Application 502: Some platforms wrap upstream crashes in their own branded error page.

How to tell whether Cloudflare or Nginx is responsible

Check the error page first. A Cloudflare-branded page often includes a Ray ID, a data center code, and text that mentions the host, browser, and Cloudflare status. A plain “502 Bad Gateway” page with “nginx” at the bottom usually means Nginx generated it.

Then run a header check:

curl -I https://example.com

Look for headers such as:

  • server: cloudflare
  • cf-ray
  • cf-cache-status
  • server: nginx

Headers do not always tell the full story, since Cloudflare may still sit in front of Nginx. Still, they help frame the first test.

If Cloudflare is enabled, test the origin directly. Use the origin IP with the correct Host header:

curl -I --resolve example.com:443:203.0.113.10 https://example.com

If the direct origin request fails with a 502, Cloudflare is probably only reporting the problem. If the direct origin request works, focus on Cloudflare-to-origin connectivity, TLS, firewall rules, or origin rate limits.

Cloudflare 502: common causes

A Cloudflare 502 often means the edge server could not complete a clean exchange with your origin. The origin may be online, but still not providing an acceptable response.

Common causes include:

  • Origin service downtime: Nginx, Apache, or the app server is stopped or crashing.
  • Firewall blocking Cloudflare IPs: The origin rejects Cloudflare edge requests.
  • TLS mismatch: Certificate problems or incompatible SSL mode settings break the handshake.
  • Port issues: The origin is not listening on the expected HTTP or HTTPS port.
  • Overloaded origin: CPU, memory, database locks, or worker exhaustion cause bad responses.
  • Invalid compression: Faulty gzip or Brotli output can trigger upstream errors.

Cloudflare gives you one useful clue: the Ray ID. Save it. It helps correlate the request with Cloudflare logs if you have access to analytics or support.

Do not skip firewall checks. It drives me crazy that many teams lose 20 or 30 minutes checking application code when the origin firewall is silently dropping Cloudflare IP ranges after a security rule update.

Nginx 502: common causes

An Nginx 502 usually means Nginx is healthy enough to answer the client, but its upstream dependency is not responding correctly.

Start with the Nginx error log:

tail -f /var/log/nginx/error.log

The wording matters. These messages point to different fixes:

  • connect() failed: The upstream service is down, blocked, or listening on a different port.
  • upstream prematurely closed connection: The application crashed or killed the connection mid-response.
  • no live upstreams: All configured upstream servers are marked unavailable.
  • upstream sent too big header: Response headers exceed Nginx buffer settings.
  • connection refused: The upstream process is not accepting connections.

Next, check the upstream service itself. For PHP sites, inspect PHP-FPM status and worker limits. For Node.js, check the process manager, memory use, and recent restarts. For Python apps, inspect Gunicorn or uWSGI logs. For Ruby apps, check Puma or Passenger.

A typical Nginx 502 pattern is simple: the web server stays up, while the app pool collapses under load. The user sees Nginx. The fault sits one layer deeper.

Best diagnostic order

Use a fixed order. Guessing wastes time.

  1. Capture the exact error page. Save the timestamp, URL, status code, and any Ray ID.
  2. Check response headers. Confirm whether Cloudflare, Nginx, or another proxy answered.
  3. Test the origin directly. Use curl with the origin IP and Host header.
  4. Read Nginx error logs. Match the timestamp exactly, preferably in UTC.
  5. Check upstream health. Confirm ports, sockets, processes, and worker counts.
  6. Review resource use. Look at CPU, RAM, disk I/O, database wait time, and connection counts.
  7. Review recent changes. Deployments, firewall updates, certificate renewals, and config edits matter.

If the issue appears only through Cloudflare, review SSL mode, origin certificates, firewall rules, and Cloudflare IP allowlists. If it appears when bypassing Cloudflare, focus on Nginx and the app stack.

Cloudflare analytics versus Nginx logs

Cloudflare analytics are useful for spotting broad patterns. You can see spikes by status code, country, data center, path, cache status, and time range. That helps answer, “How many users were affected?”

Nginx logs are better for root cause work. They show upstream timing, connection failures, request paths, client IPs, and exact error messages. That helps answer, “What broke?”

For serious incident response, use both. Cloudflare may show that 8,400 requests failed between 10:05 and 10:17. Nginx may show that PHP-FPM hit its pm.max_children limit at 10:04. Together, that is a clean incident timeline.

Fixes that actually work

For Cloudflare-related 502 errors, confirm that the origin accepts traffic from Cloudflare IP ranges. Check SSL mode. Renew certificates before expiry. Make sure the origin is not rate-limiting Cloudflare edge addresses as if they were attackers.

For Nginx-related 502 errors, restart the failed upstream only as a short-term action. Then find why it failed. Increase worker limits if they are too low. Tune timeouts if long requests are valid. Fix oversized headers if authentication cookies are bloated. Check database latency if app workers are stuck waiting.

Also review these Nginx directives when symptoms match:

  • proxy_connect_timeout
  • proxy_read_timeout
  • proxy_send_timeout
  • fastcgi_read_timeout
  • proxy_buffer_size
  • proxy_buffers

Do not raise every timeout blindly. Longer timeouts can hide a slow application and keep users waiting. Measure first.

Prevention and monitoring

Good monitoring catches many 502 incidents before users report them. Track origin health from outside Cloudflare and from inside the private network. Monitor Nginx upstream response time, 5xx rate, worker saturation, memory, and restart counts.

Set alerts for small but meaningful thresholds. For example, alert if 502 responses exceed 1% of requests for five minutes, or if upstream response time doubles compared with the previous hour. That is early enough to act, but not so sensitive that every deploy wakes the team.

The practical rule is simple: Cloudflare tells you where users felt the failure; Nginx usually tells you why it happened. Start at the visible error, confirm the source, then work inward one layer at a time. That method is slower than guessing for the first sixty seconds. After that, it wins.