# Cloudflare Tunnel Debugging

Common failure modes and diagnostic steps for cloudflared tunnels on Tencent Cloud servers.

## 502 Bad Gateway

**Root cause**: Tunnel is running but can't reach the origin service. Two variants:

### Variant A: Token-based tunnel, port mismatch

When the tunnel runs with `--token`, ingress rules are configured in the **Cloudflare Zero Trust dashboard** (remotely), NOT in local `config.yml`. Local config file edits have no effect.

**Diagnose**:
```bash
# Check what's actually running
ps aux | grep cloudflared | grep -v grep

# Token-based tunnel will show: cloudflared tunnel ... run --token <token>
# Config-based tunnel will show: cloudflared tunnel run <name>

# Check tunnel logs for the origin it's trying to reach
cat /tmp/cf-*.log 2>/dev/null | tail -20
# Look for: originService=http://localhost:PORT
# Compare with: ss -tlnp | grep PORT
```

**Fix**: Either update the ingress URL in the Cloudflare dashboard, or move your app to the port the tunnel expects.

### Variant B: App not running

```bash
# Check if app is listening
ss -tlnp | grep <expected_port>
curl -s -o /dev/null -w "HTTP %{http_code}" http://localhost:<port>
```

### Variant C: Nginx in between, proxy target wrong

If tunnel → Nginx → app, check Nginx proxy_pass:
```bash
grep proxy_pass /etc/nginx/sites-enabled/*
sudo nginx -t && sudo nginx -s reload
```

## Tunnel Won't Start

- **Pre-checks hanging**: Always use `--no-prechecks`. The QUIC/HTTP reachability probes time out from behind GFW.
- **QUIC failures**: Use `--protocol http2`. QUIC connections through GFW are unreliable.
- **Cert errors**: `--token` tunnels don't need `cert.pem`. Use `--no-autoupdate` to avoid version-check timeouts.

## Full Diagnostic Command

```bash
echo "=== Tunnel Process ===" && ps aux | grep cloudflared | grep -v grep && \
echo "=== Tunnel Logs ===" && cat /tmp/cf-*.log 2>/dev/null | tail -10 && \
echo "=== App Ports ===" && ss -tlnp | grep -E '3000|5000|8001' && \
echo "=== Nginx ===" && grep proxy_pass /etc/nginx/sites-enabled/* 2>/dev/null
```
