Error Medic

Troubleshooting Cloudflare 502 Bad Gateway and Connection Errors

Learn how to diagnose and fix Cloudflare 502 Bad Gateway, 503 Service Unavailable, 504 Gateway Timeout, SSL handshake failures, and other connection errors.

Last updated:
Last verified:
1,532 words
Key Takeaways
  • Cloudflare 502 and 504 errors almost always indicate an issue with your origin web server, not Cloudflare itself.
  • SSL Handshake Failed (Error 525 or 526) usually means the SSL certificate on your origin server is expired, invalid, or misconfigured.
  • Connection Refused or Timed Out (Error 522) typically points to firewall rules on your origin blocking Cloudflare's IP addresses.
  • Always verify your origin server's health, firewall settings, and SSL configuration before changing Cloudflare DNS or proxy settings.
Diagnostic Approaches for Cloudflare Errors
MethodWhen to UseTimeRisk
Bypass Cloudflare (Grey Cloud)To determine if the error originates from Cloudflare or your server.5-10 minsMedium (Exposes origin IP)
Check Origin Web Server LogsWhen seeing 502, 503, or 504 errors to pinpoint server-side crashes.10-20 minsLow
Verify Firewall Rules (iptables/UFW)For Connection Refused (521) or Connection Timed Out (522) errors.5-15 minsLow
Test Origin SSL CertificateWhen encountering SSL Handshake Failed (525/526).5 minsLow

Understanding Cloudflare Connection Errors

When you place Cloudflare in front of your web server, it acts as a reverse proxy. This means client requests hit Cloudflare's edge network, and Cloudflare forwards those requests to your origin server. When things go wrong, Cloudflare returns specific HTTP status codes to the client. Understanding these codes is the first step in troubleshooting.

Error 502: Bad Gateway (and Error 520)

A 502 Bad Gateway or a Cloudflare Error 520 (Web server is returning an unknown error) signifies that Cloudflare connected to your origin server, but the origin server returned an empty, unknown, or unexpected response.

Common Causes:

  • Your origin web server (Nginx, Apache, Node.js, etc.) process crashed during the request.
  • PHP-FPM or similar application servers are exhausted and terminating connections abruptly.
  • TCP connection resets from the origin server.
  • Incompatible HTTP headers sent by the origin.

Error 503: Service Unavailable

A 503 error usually means your origin server is temporarily overloaded or undergoing maintenance. Unlike a 502, the server is actively rejecting the connection or explicitly responding with a 503 status code.

Common Causes:

  • Rate limiting rules triggering on the origin server.
  • The application server (like Tomcat, Gunicorn, or PHP-FPM) has reached its maximum connection pool limit.
  • Planned maintenance mode is active on the origin web server.

Error 504: Gateway Timeout (and Error 524)

A 504 Gateway Timeout or Cloudflare Error 524 (A timeout occurred) indicates that Cloudflare successfully connected to the origin server, but the origin server did not provide an HTTP response within the default 100-second timeout period.

Common Causes:

  • Long-running database queries blocking the application thread.
  • Heavy background processing (like generating a large report or resizing images) occurring synchronously within the HTTP request lifecycle.
  • The origin server is simply too overwhelmed to process the request in time.

Error 521 & 522: Connection Refused / Timed Out

  • Error 521 (Web server is down): Cloudflare attempted to connect to your origin on port 80 or 443, but received a connection refused error. The origin web server process might be stopped, or a firewall is actively rejecting the connection.
  • Error 522 (Connection timed out): Cloudflare could not establish a TCP connection to the origin server. The TCP SYN packets are being dropped, usually due to a firewall silently dropping packets or routing issues at the origin's hosting provider.

Error 525 & 526: SSL Handshake Failed / Invalid SSL Certificate

These errors occur when Cloudflare is configured to use 'Full' or 'Full (Strict)' SSL mode, but it cannot securely connect to your origin server.

  • Error 525 (SSL handshake failed): The origin server did not negotiate a valid SSL/TLS handshake. This can happen if the origin server does not support the cipher suites Cloudflare requires or if SNI is misconfigured.
  • Error 526 (Invalid SSL certificate): Under 'Full (Strict)' mode, Cloudflare verifies the origin certificate. If it's expired, self-signed (without being a Cloudflare Origin CA cert), or the hostname doesn't match, this error is thrown.

Step-by-Step Troubleshooting Guide

Step 1: Isolate the Issue (Bypass Cloudflare)

The quickest way to determine if the issue is with Cloudflare's configuration or your origin server is to bypass Cloudflare entirely. You can do this by editing your local hosts file to point your domain directly to your origin server's IP address.

  1. Find your origin server IP address.
  2. Open your hosts file (/etc/hosts on Linux/macOS, C:\Windows\System32\drivers\etc\hosts on Windows).
  3. Add a line: <Origin_IP> example.com www.example.com
  4. Flush your DNS cache and open the site in an Incognito window.

If you still see errors (like 500 Internal Server Error, connection refused, etc.), the problem is entirely on your origin server. If the site loads perfectly, the issue lies in the interaction between Cloudflare and your origin.

Step 2: Investigate Origin Server Logs

If the issue is on your origin, start by checking the web server and application logs.

For Nginx: tail -f /var/log/nginx/error.log

For Apache: tail -f /var/log/apache2/error.log (Debian/Ubuntu) tail -f /var/log/httpd/error_log (CentOS/RHEL)

Look for Out of Memory (OOM) killer invocations, segfaults, or application tracebacks indicating why the server failed to respond properly (causing 502s) or took too long (causing 504s).

Step 3: Verify Cloudflare IPs in Firewall

If you are seeing Error 521 (Connection Refused) or 522 (Connection Timed Out), your origin server's firewall (iptables, UFW, firewalld, or a cloud provider security group) might be blocking Cloudflare's IP addresses. Cloudflare uses a specific range of IPs to proxy traffic.

You must ensure that traffic from Cloudflare's IP ranges (available at https://www.cloudflare.com/ips/) is allowed on ports 80 and 443.

Step 4: Fix SSL/TLS Misconfigurations

If you encounter Error 525 or 526, check your Cloudflare SSL/TLS encryption mode.

  • If you have no SSL certificate on your origin, you MUST use Flexible mode (not recommended for security).
  • If you have a self-signed certificate on your origin, use Full mode.
  • If you have a valid, publicly trusted certificate or a Cloudflare Origin CA certificate on your origin, use Full (Strict) mode.

To debug origin SSL issues, you can use openssl directly against your origin IP to see what certificate it is presenting.

Step 5: Address High Latency and Packet Loss

Sometimes users report 'Cloudflare high latency' or 'Cloudflare packet loss'. Often, this is an issue between the user's ISP and the nearest Cloudflare edge data center, rather than an issue with your site specifically.

However, it can also manifest if your origin server is extremely slow to respond (high Time to First Byte - TTFB). Cloudflare caches static assets, but dynamic HTML generation must still be processed by your origin. Optimize your database queries, implement application-level caching (Redis/Memcached), and consider using Cloudflare's APO (Automatic Platform Optimization) or Page Rules to cache HTML if appropriate.

Frequently Asked Questions

bash
# Diagnostic commands for investigating Cloudflare connection errors

# 1. Check if the origin server is listening on ports 80 and 443
sudo netstat -tulpn | grep -E ':(80|443)'
# or use ss
sudo ss -tulpn | grep -E ':(80|443)'

# 2. Test origin server response bypassing Cloudflare (replace IP and DOMAIN)
curl -Iv -H "Host: yourdomain.com" http://<ORIGIN_IP_ADDRESS>/
curl -Iv --resolve yourdomain.com:443:<ORIGIN_IP_ADDRESS> https://yourdomain.com/

# 3. Test SSL Handshake directly to the origin server
openssl s_client -connect <ORIGIN_IP_ADDRESS>:443 -servername yourdomain.com

# 4. Allow Cloudflare IPs in UFW (Ubuntu/Debian firewall)
# Note: This is a shortened list for example purposes. Always fetch the full list from https://www.cloudflare.com/ips-v4
for cfip in 173.245.48.0/20 103.21.244.0/22 103.22.200.0/22 103.31.4.0/22 141.101.64.0/18 108.162.192.0/18 190.93.240.0/20 188.114.96.0/20 197.234.240.0/22 198.41.128.0/17 162.158.0.0/15 104.16.0.0/13 104.24.0.0/14 172.64.0.0/13 131.0.72.0/22; do
  sudo ufw allow from $cfip to any port 80,443 proto tcp
done
sudo ufw reload
E

Error Medic Editorial

Error Medic Editorial is a team of Senior Site Reliability Engineers and DevOps practitioners dedicated to solving complex infrastructure and networking challenges. With decades of combined experience managing high-traffic web applications, we provide actionable, production-ready solutions.

Sources

Related Articles in Cloudflare

Explore More Networking Guides