I used to run a bastion host. It sat in a public subnet, listened on port 22, ran fail2ban, and required SSH keys to log in. Every quarter someone would scan it, every year or so someone would find an OpenSSH CVE, and every six months I'd rotate keys because an engineer left. The bastion host existed because the alternative-exposing every internal service to the internet-was worse. Then I found Cloudflare Tunnel, and now I don't have a bastion host at all.
Cloudflare Tunnel (the product) and cloudflared (the daemon) flip the network direction. Instead of your server listening on a public port and waiting for inbound connections, cloudflared opens an outbound tunnel to Cloudflare's edge. Traffic from the internet hits Cloudflare, flows back through that tunnel, and reaches your internal service. No open ports. No public IP. No bastion. Your firewall can deny all inbound traffic and the service still serves the public internet.
What a Tunnel Actually Does
CodeCopy
Public Internet
│
▼
┌───────────────────┐
│ Cloudflare Edge │ (any of 300+ cities)
│ - TLS termination│
│ - WAF / DDoS │
│ - Access (SSO) │
└─────────┬─────────┘
│ outbound tunnel (HTTP/2 over QUIC)
│ initiated by cloudflared
▼
┌───────────────────┐
│ cloudflared daemon│ (your VPS, laptop, k8s pod)
│ - ingress rules │
│ - local routing │
└─────────┬─────────┘
│ plain HTTP to localhost
▼
┌───────────────────┐
│ Your service │ (localhost:8080, etc.)
│ - no public port │
│ - no inbound FW │
└───────────────────┘
The key insight is the direction of the connection. Your server dials out to Cloudflare. From the firewall's perspective, that's outbound HTTPS-almost always allowed. From the internet's perspective, your service is reachable via a Cloudflare hostname, but its origin IP is invisible. Attackers can't port-scan what they can't see.
When to Use a Tunnel (and When Not To)
| Use case | Tunnel fits? | Why |
|---|---|---|
| Expose a homelab service to the internet | Yes | No port forwarding, dynamic IP doesn't matter |
| Replace a bastion host for SSH/RDP | Yes | Cloudflare Access + cloudflared SSH proxy |
| Production web app with WAF + DDoS | Yes | Cloudflare's edge handles both for free |
| Internal admin UI with SSO | Yes | Cloudflare Access gives you Google/GitHub SSO for free |
| Local dev server shared with a stakeholder | Yes | cloudflared tunnel --url http://localhost:3000 |
| High-throughput binary streaming (video upload) | Maybe | Tunnel adds latency; test before committing |
| Real-time gaming with sub-30ms requirement | No | Edge hop adds 10-50ms; use direct connections |
| Compliance requiring data residency in your DC | No | Traffic transits Cloudflare's edge |
The pattern: tunnels shine for HTTP(S) traffic where you want security and convenience more than absolute minimum latency. They're less ideal for ultra-low-latency or compliance-constrained workloads.
Prerequisites
- A Cloudflare account. The free tier covers most personal and small-team use; Teams/Zero Trust is what you want for SSO and audit logging.
- A domain managed by Cloudflare (i.e., the domain's nameservers point to Cloudflare). Tunnels use Cloudflare DNS to route traffic.
- A machine to run
cloudflaredon. This can be your laptop, a VPS, a Docker container, or a Kubernetes pod. - Internal services you want to expose, listening on localhost or a private network. The whole point is that they don't need to be publicly reachable.
You don't need a public IP, you don't need port forwarding, and you don't need to open firewall rules. That's the appeal.
Installing cloudflared
cloudflared is a single Go binary. Install it the way that fits your OS:
BashCopy
shell
macOS (Homebrew)
brew install cloudflared
Debian/Ubuntu (apt)
curl -fsSL https://pkg.cloudflare.com/cloudflare-main.gpg \
| sudo tee /usr/share/keyrings/cloudflare-main.gpg >/dev/null
echo "deb [signed-by=/usr/share/keyrings/cloudflare-main.gpg] https://pkg.cloudflare.com/cloudflared $(lsb_release -cs) main" \
| sudo tee /etc/apt/sources.list.d/cloudflared.list
sudo apt-get update && sudo apt-get install -y cloudflared
Arch / Manjaro
pacman -S cloudflared
Any Linux (binary)
curl -fsSL https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-amd64 \
-o /usr/local/bin/cloudflared
chmod +x /usr/local/bin/cloudflared
Verify
cloudflared --version
markdown
The binary is statically linked, so you can drop it on any Linux and it'll run. I keep a copy in /usr/local/bin on every server I manage.
Quick Tunnel: The 30-Second Demo
If you just want to share localhost:3000 with someone for five minutes, use a quick tunnel. No account, no DNS, no config file:
BashCopy
shell
Start your local service
npm run dev # listening on http://localhost:3000
Expose it via a trycloudflare.com URL
cloudflared tunnel --url http://localhost:3000
plaintext
cloudflared prints something like:
CodeCopy
plaintext
+--------------------------------------------------------------------------------------------+
| Your quick Tunnel has been created! Visit it at: |
| https://random-words-1234.trycloudflare.com |
+--------------------------------------------------------------------------------------------+
markdown
Hand that URL to your teammate. They hit https://random-words-1234.trycloudflare.com and see your local dev server. TLS is handled by Cloudflare. No port forwarding on your router, no Ngrok subscription, no exposing your home IP.
The catch: the URL is random, ephemeral, and not for production. If cloudflared restarts, you get a new URL. For anything durable, you want a named tunnel.
Named Tunnel: The Production Setup
Named tunnels are persistent, route to your own domain, and survive restarts. Here's the full setup.
Authenticate and create the tunnel
BashCopy
shell
Authenticate (opens browser, saves cert to ~/.cloudflared/cert.pem)
cloudflared tunnel login
Create a named tunnel
cloudflared tunnel create prod-services
Output:
Created tunnel prod-services with id 1a2b3c4d-5e6f-7890-abcd-ef1234567890
Credentials written to ~/.cloudflared/1a2b3c4d-5e6f-7890-abcd-ef1234567890.json
markdown
The credentials file is the tunnel's identity. Anyone with that file can run a tunnel with the same ID. Treat it like a private key.
Create a config file
~/.cloudflared/config.yml:
YAMLCopy
yaml
tunnel: 1a2b3c4d-5e6f-7890-abcd-ef1234567890
credentials-file: /root/.cloudflared/1a2b3c4d-5e6f-7890-abcd-ef1234567890.json
Route multiple hostnames to different local services
ingress:
# Production app -> localhost:8080
- hostname: app.example.com service: http://localhost:8080
# API -> localhost:9000
- hostname: api.example.com service: http://localhost:9000
# Grafana -> localhost:3000 (will add Access auth later)
- hostname: grafana.example.com service: http://localhost:3000
# SSH for a private host
- hostname: ssh.example.com service: ssh://localhost:22
# Catch-all must be last and must return 404
- service: http_status:404
plaintext
Create DNS records
BashCopy
plaintext
Cloudflared writes the CNAMEs for you
cloudflared tunnel route dns prod-services app.example.com
cloudflared tunnel route dns prod-services api.example.com
cloudflared tunnel route dns prod-services grafana.example.com
cloudflared tunnel route dns prod-services ssh.example.com
markdown
Each command creates a CNAME <hostname> → <tunnel-id>.cfargotunnel.com in your Cloudflare DNS. Traffic to those hostnames flows through your tunnel.
Validate and run
BashCopy
shell
Validate the config
cloudflared tunnel ingress validate
Run the tunnel
cloudflared tunnel run prod-services
markdown
Now https://app.example.com proxies to localhost:8080 on the machine running cloudflared. TLS is terminated at Cloudflare's edge. Your server only sees outbound HTTPS.
Running as a Systemd Service
For production you want cloudflared to start on boot and restart on crash. Use the built-in service installer:
BashCopy
shell
Install as systemd service (Linux)
sudo cloudflared service install
Start / enable
sudo systemctl enable cloudflared
sudo systemctl start cloudflared
sudo systemctl status cloudflared
plaintext
The installer copies your config to /etc/cloudflared/config.yml and the credentials to /etc/cloudflared/<tunnel-id>.json. Logs go to journald:
BashCopy
shell
sudo journalctl -u cloudflared -f
markdown
I keep a copy of the systemd unit (generated by cloudflared service install) in version control alongside the app, so a new server can be provisioned with the tunnel already configured.
Docker Deployment
If you prefer containers, the official image is cloudflare/cloudflared. Here's a docker-compose.yml that exposes three local services:
YAMLCopy
yaml
version: "3.9"
services:
cloudflared:
image: cloudflare/cloudflared:latest
restart: unless-stopped
command: tunnel run
environment:
TUNNEL_TOKEN: ${TUNNEL_TOKEN}
# If using a config file instead of a token, mount it:
# volumes:
# - ./cloudflared-config.yml:/etc/cloudflared/config.yml:ro
# - ./credentials.json:/etc/cloudflared/credentials.json:ro
networks:
- internal
app:
image: myapp:latest
restart: unless-stopped
networks:
- internal # No ports: published - cloudflared reaches it via the internal network
api:
image: myapi:latest
restart: unless-stopped
networks:
- internal
networks:
internal:
driver: bridge
plaintext
The cleaner approach is the remotely-managed tunnel, where you configure ingress rules in the Cloudflare dashboard (or via API) and cloudflared just needs a token. Generate the token in the Zero Trust dashboard under Networks → Tunnels → Create a tunnel.
BashCopy
shell
Run with a token (no config file needed locally)
docker run -d --name cloudflared --restart unless-stopped \
cloudflare/cloudflared:latest tunnel --no-autoupdate run --token ${TUNNEL_TOKEN}
markdown
The --token approach is what I use in production. The config lives in Cloudflare, survives server rebuilds, and is editable without SSH.
Kubernetes Deployment
For K8s, deploy cloudflared as a DaemonSet so every node runs a tunnel pod. The tunnel is lightweight (~50MB RAM, negligible CPU) and provides redundancy-if one node dies, traffic shifts to the others via Cloudflare's load balancing.
YAMLCopy
yaml
apiVersion: apps/v1
kind: DaemonSet
metadata:
name: cloudflared
namespace: kube-system
spec:
selector:
matchLabels:
app: cloudflared
template:
metadata:
labels:
app: cloudflared
spec:
containers:
- name: cloudflared image: cloudflare/cloudflared:2024.10.0 args:
- tunnel
- --no-autoupdate
- --metrics
- 0.0.0.0:36500
- run env:
- name: TUNNEL_TOKEN valueFrom: secretKeyRef: name: cloudflared-token key: token resources: requests: cpu: 10m memory: 32Mi limits: cpu: 200m memory: 128Mi livenessProbe: httpGet: path: /ready port: 36500 initialDelaySeconds: 10 periodSeconds: 10 readinessProbe: httpGet: path: /ready port: 36500 initialDelaySeconds: 5 periodSeconds: 5 --- apiVersion: v1 kind: Secret metadata: name: cloudflared-token namespace: kube-system type: Opaque stringData: token: "eyJhIjoi..." # your tunnel token
markdown
The --metrics 0.0.0.0:36500 flag exposes a Prometheus endpoint. Cloudflare's pods register with the edge and automatically load-balance traffic. If you scale the cluster from 3 nodes to 10, you get 7 more tunnel connections for free.
Cloudflare Access: Identity-Aware Auth for Free
The thing that makes tunnels really shine is Cloudflare Access. It's an identity-aware proxy that sits in front of your tunnel and requires SSO authentication before letting traffic through. Free for up to 50 users.
CodeCopy
plaintext
Browser -> Cloudflare Edge -> Access (SSO check) -> Tunnel -> Your service
│
├── Google / GitHub / Okta / SAML login
├── Group-based policy (e.g., "engineers only")
└── Per-app policy (e.g., "grafana requires @company.com")
markdown
To set it up, in the Zero Trust dashboard:
- Go to Access → Applications → Add an application.
- Choose "Self-hosted" and enter
grafana.example.comas the application domain. - Choose an identity provider (Google workspace, GitHub org, Okta, etc.).
- Add a policy: "Allow users in group
engineers@company.com." - Save.
Now https://grafana.example.com redirects unauthenticated users to Google login, verifies they're in your org's engineers group, and only then proxies them through to your Grafana instance. Grafana itself sees requests from cloudflared's IP and can disable its own login.
For SSH, the same pattern works with the cf ssh client, which proxies your SSH connection through Access. You get MFA on every SSH login without ever exposing port 22 to the internet.
Local Development: Sharing a Branch Without Deploying
This is one of my favorite uses. You're working on a feature branch, a designer wants to see it, and you don't want to deploy to staging. Run a quick tunnel:
BashCopy
shell
Start your dev server
pnpm dev # http://localhost:3000
Expose it on a stable URL tied to your domain
cloudflared tunnel --url http://localhost:3000 \
--hostname feature-branch.yourdomain.com
plaintext
Now https://feature-branch.yourdomain.com shows your local dev server. The designer sees live updates as you save files. No deploy, no preview environment, no waiting for CI.
I script this into my dev workflow:
BashCopy
shell
!/usr/bin/env bash
bin/preview - share local dev on a stable URL
set -euo pipefail
BRANCH=$(git rev-parse --abbrev-ref HEAD | tr '/' '-')
HOSTNAME="${BRANCH}.preview.yourdomain.com"
echo "Sharing http://localhost:3000 on https://${HOSTNAME}"
cloudflared tunnel --url http://localhost:3000 --hostname "${HOSTNAME}"
markdown
Engineers on the team can each share branches this way, and the URLs are predictable enough to use in PR descriptions.
Replacing a Bastion Host for SSH
The classic bastion pattern: SSH to bastion, then SSH from bastion to internal hosts. With cloudflared, you do it differently.
On each internal host, run cloudflared configured to proxy SSH:
YAMLCopy
yaml
/etc/cloudflared/config.yml on internal host
tunnel: internal-ssh
credentials-file: /etc/cloudflared/credentials.json
ingress:
- hostname: host1.internal.example.com service: ssh://localhost:22
- service: http_status:404
plaintext
From your laptop, configure ~/.ssh/config:
CodeCopy
ssh
Host *.internal.example.com
ProxyCommand cloudflared access ssh --hostname %h
User youruser
IdentityFile ~/.ssh/id_ed25519
markdown
Now ssh host1.internal.example.com:
- Triggers
cloudflared access ssh, which opens a browser for SSO (or uses a cached token). - Once authenticated, your SSH connection flows through Cloudflare's edge to the
cloudflareddaemon onhost1, which proxies it tolocalhost:22. - Standard SSH auth (key, MFA) happens between you and the host.
No public port 22, no bastion, no jump host, and every SSH attempt is logged in Cloudflare Access's audit log. This is what zero-trust networking actually looks like in practice.
Monitoring and Metrics
cloudflared exposes a Prometheus metrics endpoint if you pass --metrics:
BashCopy
shell
cloudflared tunnel run --metrics 0.0.0.0:36500 prod-services
markdown
Useful metrics:
-
cloudflared_tunnel_request_total- request count by status code -
cloudflared_tunnel_request_duration_seconds- request latency histogram -
cloudflared_tunnel_server_locations- count of connections to each Cloudflare colo -
cloudflared_tunnel_ha_connections- number of active HA connections (should be 4+)
A minimal Grafana alert: alert if cloudflared_tunnel_ha_connections drops below 2 (the tunnel is degraded) or if rate(cloudflared_tunnel_request_total{status=~"5.."})[5m] exceeds your normal 5xx rate.
Also watch the cloudflared logs for "Registered tunnel connection" messages. A healthy tunnel shows 4 connections registered to different Cloudflare colos. Fewer than 4 means the tunnel is degraded.
Common Mistakes
Forgetting the catch-all 404 rule at the end of the ingress. The ingress list is evaluated top-to-bottom, and the last rule must be a catch-all (service: http_status:404). Without it, cloudflared refuses to start. I've lost 20 minutes to this more than once.
Mounting credentials in a public Docker image. The credentials JSON is a secret. Build it into your image and you've handed the tunnel to anyone who pulls the image. Use a Secret mount or an env var.
Running cloudflared as root unnecessarily. It doesn't need root. Create a cloudflared user and run the service as that user. The systemd unit supports User=cloudflared.
Expecting the tunnel to make a slow origin fast. cloudflared adds one network hop (your server → Cloudflare edge → user). If your origin takes 2 seconds to respond, the user still waits 2 seconds. The tunnel helps with security and DDoS, not with origin latency.
Trusting Cloudflare's TLS for everything. The traffic between user and Cloudflare is TLS. The traffic between Cloudflare and cloudflared is also encrypted (the tunnel protocol). But the traffic between cloudflared and your local service (e.g., http://localhost:8080) is plain HTTP unless you configure it otherwise. If cloudflared runs on a different host than your service, use HTTPS or a private network.
Forgetting to set --no-autoupdate in containers. The container image already has a pinned version; cloudflared will try to update itself, fail (no write permissions), and waste log lines. Always pass --no-autoupdate in container deployments.
Pointing DNS at the tunnel before it's running. If you create the CNAME and then take your time standing up cloudflared, visitors get a 502 from Cloudflare. Stand up the tunnel first, then route DNS to it.
Troubleshooting
"502 Bad Gateway from Cloudflare." The tunnel is up but cloudflared can't reach your local service. Check cloudflared's logs for "error="ingress"" messages. Verify the local service is listening on the address in your ingress rule. Common gotcha: ingress says http://localhost:8080 but the service binds to 127.0.0.1:8080 only and cloudflared runs in a container where localhost is the container.
"Tunnel connects but I get connection reset." Check that your service isn't crashing or rejecting requests. Also check Cloudflare Access policies-your IP might not be allowed.
"cloudflared tunnel login opens a browser that won't load." You're probably running on a headless server. Run cloudflared tunnel login on your laptop instead, then copy ~/.cloudflared/cert.pem to the server.
"SSH via cloudflared is slow." Each SSH command opens a fresh Access check the first time. After that, the token is cached for the session. For frequent SSH, use ControlMaster in your ~/.ssh/config to reuse the connection:
CodeCopy
ssh
Host *.internal.example.com
ProxyCommand cloudflared access ssh --hostname %h
ControlMaster auto
ControlPath ~/.ssh/cm-%r@%h:%p
ControlPersist 10m
markdown
"My tunnel works from my laptop but not from the server." Likely a DNS issue. Cloudflare DNS records take a minute or two to propagate after cloudflared tunnel route dns. Wait and retry.
"The tunnel randomly disconnects." Check your server's network. cloudflared is robust to brief outages (it reconnects automatically), but sustained packet loss will cause disconnects. Also check if your firewall is doing connection tracking with aggressive timeouts on long-lived idle connections-QUIC tunnels can look idle.
Cost Considerations
Cloudflare Tunnel itself is free for unlimited traffic on the free plan. What you pay for:
| Feature | Free | Zero Trust (paid) |
|---|---|---|
| Tunnel daemon | ✓ | ✓ |
| Unlimited bandwidth | ✓ | ✓ |
| WAF + DDoS | ✓ | ✓ |
| Cloudflare Access (SSO) | Up to 50 users | $7/user/month |
| Audit logs | 24h retention | 1+ year |
| Device posture (WARP client) | - | Included |
| Team namespaces / RBAC | - | Included |
For a small team (<50 people), you can run your entire zero-trust setup on the free tier. For larger orgs, the $7/user/month for Access is competitive against Okta + bastion host + VPN costs, and you get audit logging for free.
Compare to alternatives:
| Solution | Monthly cost | Open ports | SSO built-in |
|---|---|---|---|
| Cloudflare Tunnel + Access (10 users) | $0-$70 | 0 | Yes |
| Bastion host on AWS t3.small + your time | $15 + ops | 22 | No |
| Tailscale (10 users) | $60 | 0 | Yes |
| Ngrok Business | $99+ | 0 | No |
| Self-hosted WireGuard + auth proxy | $5 + ops | 1 (UDP) | No |
For most teams, Cloudflare Tunnel wins on cost and operational simplicity. Tailscale is the closest competitor and is genuinely good-I've used both.
Alternatives
- Tailscale - WireGuard-based mesh VPN. Excellent for connecting machines to each other; less ideal for exposing a service to the public internet. Pairs well with Cloudflare (Tailscale for machine-to-machine, Cloudflare for public ingress).
- Ngrok - Similar concept, easier quick-tunnel UX, but expensive for production use. The free tier has random URLs and rate limits.
- WireGuard + reverse proxy - Roll your own. You own the keys, you own the latency, and you own the maintenance burden. Use this if Cloudflare's edge is a dealbreaker for compliance.
- AWS Verified Access - Cloud-native equivalent if you're all-in on AWS. Tight integration with IAM and identity providers, but locked to AWS.
- Inlets (PRO) - TCP/HTTP tunnel with a self-hosted server. Good when you need to control both ends; the PRO version supports TCP, which Cloudflare doesn't (without Cloudflare Spectrum).
For HTTP(S) exposure with identity-aware auth on a custom domain, Cloudflare Tunnel is hard to beat.
Real-World Use Case: Self-Hosting Without a Public IP
I run a home server on a residential ISP. My IP is dynamic, port 80/443 are blocked by the ISP, and my IP changes every few weeks. None of this matters with Cloudflare Tunnel.
CodeCopy
plaintext
Home server (192.168.1.100)
├── cloudflared -> outbound tunnel to Cloudflare edge
├── Caddy (port 80) -> serves internal services
├── Gitea (port 3000) -> git.company.net
├── Vaultwarden (8222) -> vault.company.net
└── Home Assistant -> home.company.net (Access-protected)
The router's firewall denies all inbound traffic. cloudflared dials out. All four services are reachable from anywhere on the internet, with TLS, WAF, and (for Home Assistant) SSO gating via Cloudflare Access. The total cost: $0.
This setup replaces a static-IP business internet plan ($20/month extra), a dynamic DNS service ($5/year), and the security exposure of open ports. It's the closest thing to free hosting you can get while still owning the hardware.
Conclusion
Cloudflare Tunnel is one of those tools that quietly changes how you architect infrastructure. Once you stop opening ports and start dialing out, the security model inverts in a useful way: instead of defending a perimeter, you eliminate it. Combined with Cloudflare Access, you get identity-aware zero-trust networking for free or near-free.
It's not the right tool for every workload, but for the 90% case of "I have an HTTP service and I want it on the internet safely," it's the best default I know.
Originally published on Mango Developer.
Top comments (1)
The direction flip is the sentence that makes the whole post click — the server dials out, so there is no public port to scan, patch, or fail2ban in the first place. Everything after that is just the consequences of that one inversion, and your when-to-use table is honest about where it stops working: sub-30ms gaming and data-residency cases are exactly where people get burned by treating a tunnel as a free VPN.
Two details I would highlight for anyone copying this into production: the catch-all 404 ingress rule that cloudflared refuses to start without, and the credentials JSON being a secret in its own right — mounting it into a public image hands the tunnel to anyone who pulls it. Your Grafana alert on cloudflared_tunnel_ha_connections dropping below 2 is also the right tripwire; a tunnel that is half-degraded still serves traffic, so it fails quietly.
One thing I would add from the Android side: for a mobile app talking to an API behind a tunnel, the extra edge hop is invisible until the origin is slow, and then everyone blames the tunnel. Do you keep your ingress rules in the Cloudflare dashboard with remotely-managed tunnels, or in a version-controlled config file, and how do you rotate the tunnel credentials when a server is rebuilt?