Error Medic

How to Fix Cloudflare 502 Bad Gateway, 504 Gateway Timeout, and Connection Errors

Comprehensive SRE guide to troubleshooting Cloudflare 502, 503, 504 errors, connection timeouts, and SSL handshake failures. Actionable fixes and root causes.

Last updated:
Last verified:
1,779 words
Key Takeaways
  • Cloudflare 502 and 504 errors typically indicate upstream timeouts or crashes at your origin server (e.g., PHP-FPM, Node.js, or database exhaustion), not a Cloudflare edge issue.
  • Connection Refused and Connection Timed Out (Error 521/522) are most often caused by origin firewalls (iptables, UFW, AWS Security Groups) blocking Cloudflare's Anycast IPs.
  • SSL Handshake Failed (Error 525) requires ensuring your origin server is presenting a valid SSL certificate and matching Cloudflare's SSL/TLS encryption mode (Full or Full Strict).
  • Bypassing Cloudflare using local host file modifications or curl --resolve is the fastest way to isolate whether an issue is at the edge or the origin.
Diagnostic Approaches for Cloudflare Errors
MethodTarget ErrorTimeRisk
Direct Origin Curl (--resolve)All 5xx Errors / Connection Reset2 minsLow
Review Origin Web/App Logs502 Bad Gateway / 503 Service Unavailable10 minsLow
Audit Firewall / UFW / Security GroupsConnection Refused / Timed Out5 minsHigh
Check SSL Cert & CF TLS ModeSSL Handshake Failed (525/526)5 minsMedium
MTR / TCPDump AnalysisHigh Latency / Packet Loss15 minsLow

Understanding Cloudflare Routing and Errors

When you place Cloudflare in front of your application, it acts as a reverse proxy. Traffic flows from the Client to the Cloudflare Edge, and then from the Edge to your Origin Server. When an error occurs, it is critical to determine whether the failure happened between the Client and Cloudflare, or between Cloudflare and your Origin.

In 99% of cases involving a cloudflare 502 bad gateway, cloudflare 504 gateway timeout, or cloudflare connection refused, the breakdown is happening on the leg between Cloudflare and your Origin Server. Cloudflare provides specific error codes (often in the 52X range) to help pinpoint the exact nature of the failure.

Decoding the Error Messages

1. Cloudflare 502 Bad Gateway & 504 Gateway Timeout

Standard HTTP 502 and 504 errors usually mean Cloudflare successfully connected to your origin server (e.g., Nginx or Apache), but your origin server failed to get a valid response from an upstream process (like PHP-FPM, a Node.js daemon, or a database).

  • 502 Bad Gateway: The upstream process crashed or returned an invalid, malformed response to the web server.
  • 504 Gateway Timeout: The upstream process took too long to respond. Cloudflare will drop connections after 100 seconds of inactivity from the origin (unless configured differently on Enterprise plans).
2. Cloudflare 503 Service Unavailable

This indicates your origin server is actively rejecting requests due to resource exhaustion (CPU/Memory limits reached), rate limiting configurations on your origin web server, or the server being placed into maintenance mode.

3. Cloudflare Connection Refused / Timed Out (Errors 521 & 522)
  • Error 521 (Web Server Is Down): Cloudflare attempted to connect to your origin on port 80 or 443, but the connection was actively refused (ECONNREFUSED). This means the server is up, but the web service (Nginx/Apache) is down or not listening on the expected ports.
  • Error 522 (Connection Timed Out): Cloudflare sent a SYN packet to the origin but never received a SYN-ACK. This is almost always a firewall issue (iptables, UFW, AWS Security Groups) dropping packets from Cloudflare IPs.
4. Cloudflare Connection Reset (Error 520)

Error 520 occurs when the origin server returns an unexpected, empty, or unknown response to Cloudflare. This frequently happens if the origin server resets the TCP connection abruptly (RST packet) due to a crash, or if headers exceed Cloudflare's limits.

5. Cloudflare SSL Handshake Failed (Errors 525 & 526)

An SSL Handshake failure occurs when Cloudflare is set to 'Full' or 'Full (Strict)' SSL/TLS mode, but it cannot negotiate a secure connection with your origin.

  • Error 525: The origin did not present a certificate, or the cipher suites do not match.
  • Error 526: The origin presented an invalid or expired certificate (often occurring when using 'Full Strict' with a self-signed cert instead of a valid Origin CA cert).
6. Cloudflare High Latency & Packet Loss

If users experience cloudflare high latency or cloudflare packet loss, the issue could be sub-optimal BGP routing between the client's ISP and the Cloudflare edge, or network congestion at your origin's datacenter. It requires utilizing tools like mtr to track packet traversal.


Step-by-Step Troubleshooting and Resolution

Step 1: Isolate the Origin Server (Bypass Cloudflare)

Before changing any configurations, verify if the origin is functioning correctly without Cloudflare. You can bypass Cloudflare's proxy by using curl with the --resolve flag, forcing your local machine to connect directly to the origin IP.

# Syntax: curl -Iv https://YOUR_DOMAIN.com --resolve YOUR_DOMAIN.com:443:YOUR_ORIGIN_IP
curl -Iv https://example.com --resolve example.com:443:192.168.1.50

If this direct request fails with a 502, 504, or Connection Refused, the issue is 100% at your origin server. If it succeeds, the issue lies in the Cloudflare configuration or network path.

Step 2: Fixing 502 and 504 Errors (Origin Upstream Tuning)

If you are seeing 502s or 504s, your web server is talking to Cloudflare, but the backend application is failing.

  1. Check System Resources: Run htop or top to check for CPU or RAM exhaustion. If out of memory (OOM), check dmesg -T | grep -i oom.
  2. Review Web Server Logs:
    • Nginx: tail -f /var/log/nginx/error.log
    • Apache: tail -f /var/log/apache2/error.log
  3. Tune Upstream Timeouts (Nginx example): If your application requires long processing times (e.g., report generation), increase the timeout values in your Nginx configuration so it doesn't close the connection before Cloudflare does.
    location / {
        proxy_read_timeout 120s;
        proxy_connect_timeout 120s;
        fastcgi_read_timeout 120s;
    }
    
  4. Increase Application Limits: For PHP, edit php.ini and increase max_execution_time. Ensure your PHP-FPM pool has enough pm.max_children to handle concurrent requests.

Step 3: Fixing Connection Timed Out / Refused (Firewall Rules)

If you receive Error 521 or 522, your firewall is likely blocking Cloudflare's Anycast IP addresses. Cloudflare proxies traffic, meaning all incoming requests to your origin will appear to come from Cloudflare IPs, not the end user's IP.

  1. Check if the Web Service is Running:
    sudo systemctl status nginx  # or apache2
    netstat -tulpn | grep -E ':(80|443)'
    
  2. Allowlist Cloudflare IPs in your Firewall: You must allow incoming TCP traffic on ports 80 and 443 from all Cloudflare IP ranges (IPv4 and IPv6). If you are using UFW, IPTables, or a cloud provider's security group (AWS, GCP), you need to script the inclusion of these IPs. (See the Code Block section for a UFW script).

Step 4: Fixing SSL Handshake Failed (Error 525/526)

The cloudflare ssl handshake failed error is a mismatch between the origin's SSL certificate and Cloudflare's SSL mode.

  1. Log into the Cloudflare Dashboard -> SSL/TLS -> Overview.
  2. Note your current mode:
    • Flexible: Cloudflare connects to your origin over HTTP (Port 80). If your origin is forcing HTTPS redirects, this causes an infinite redirect loop.
    • Full: Cloudflare connects via HTTPS. The origin must have an SSL certificate, but it can be self-signed.
    • Full (Strict): The origin must have a valid certificate signed by a trusted CA or Cloudflare Origin CA.
  3. The Fix: Generate a free Cloudflare Origin CA certificate from the dashboard, install it on your origin server (Nginx/Apache), and set the Cloudflare SSL mode to Full (Strict). This provides end-to-end encryption without CA verification errors.

Step 5: Diagnosing High Latency and Packet Loss

If users report cloudflare high latency or intermittent cloudflare connection reset issues:

  1. Run MTR (My Traceroute): Ask the affected user to run an MTR to your domain to identify where the packet loss is occurring (ISP, transit provider, or Cloudflare edge).
  2. Analyze TCP Keepalive: Ensure your origin server supports TCP Keepalive. Cloudflare reuses connections to your origin to reduce latency. If your origin aggressively closes idle connections, it results in 520 Connection Reset errors. In Nginx, ensure keepalive_timeout is set to at least 60 seconds.
    keepalive_timeout 65;
    keepalive_requests 1000;
    

By systematically verifying the origin bypassing Cloudflare, checking resources, auditing firewalls, and aligning SSL configurations, you can resolve virtually all Cloudflare-related gateway and connection errors.

Frequently Asked Questions

bash
#!/bin/bash
# Script to automate allowlisting Cloudflare IPs in UFW firewall to prevent 521/522 Connection Refused errors.

echo "Fetching Cloudflare IPv4 addresses..."
curl -s https://www.cloudflare.com/ips-v4 -o /tmp/cf_ips_v4
echo "Fetching Cloudflare IPv6 addresses..."
curl -s https://www.cloudflare.com/ips-v6 -o /tmp/cf_ips_v6

echo "Applying UFW rules for Cloudflare IPs..."
for ip in $(cat /tmp/cf_ips_v4); do
  sudo ufw allow from $ip to any port 80,443 proto tcp comment 'Cloudflare IPv4'
done

for ip in $(cat /tmp/cf_ips_v6); do
  sudo ufw allow from $ip to any port 80,443 proto tcp comment 'Cloudflare IPv6'
done

sudo ufw reload
echo "Cloudflare IPs successfully allowlisted. Connection Refused errors should be resolved."
E

Error Medic Editorial

Error Medic Editorial is a team of Senior Site Reliability Engineers (SREs) and Systems Administrators specializing in high-availability web infrastructure, CDN configuration, and complex network troubleshooting.

Sources

Related Articles in Cloudflare

Explore More Networking Guides