How to Install and Configure Cloudflare Tunnel (cloudflared) on Linux: Securely Expose Local Web Servers to the Internet Without Opening Ports

Network tutorial - IT technology blog
Network tutorial - IT technology blog

Real-World Problem: The Headache of Exposing Internal Web Services

About six months ago, our team set up a small on-premises server cluster in our office. It hosted a variety of services: an internal GitLab instance, staging environments for client feature reviews, and several bots listening for webhooks from GitHub and Stripe. The challenge sounded familiar: how could we allow external access to these web apps via custom domains without turning our corporate network into an easy target for hackers?

In practice, the rollout ran into endless roadblocks. Our office was on a small business broadband plan with a dynamic IP that changed every 24 to 48 hours. Worse, two branch offices were stuck behind Carrier-Grade NAT (CGNAT) from our ISPs (Viettel and VNPT). Their modems did not even have dedicated public WAN IP addresses to point our domain records to.

Initially, I opted for a quick fix: configuring Dynamic DNS (DDNS) alongside port forwarding on our DrayTek Vigor 2925 router. It turned into an absolute disaster. During peak business hours—around 10 AM and 3 PM—the router had to juggle NAT translations for more than 120 employee machines while simultaneously taking the brunt of inbound traffic from the outside world.

The router’s CPU spiked to 98–100%, and internal ping times jumped from 2ms to over 300ms. Packet loss rates hit 15–20%, triggering continuous 504 gateway timeout errors on incoming webhooks from our partners. To top it off, within 48 hours of exposing ports 80 and 443, our firewall logs recorded thousands of vulnerability scans from botnets across the globe.

Root Cause Analysis: Why the Traditional Approach Is Too Risky

The traditional port-forwarding model introduces three critical bottlenecks on office network infrastructure:

  • Exposing Inbound Ports Directly to the Internet: Opening ports on your router puts your company’s gateway IP on full display to the world. If your internal Nginx instance carries an unpatched CVE or your backend application has an injection vulnerability, attackers can breach your local network directly.
  • Hitting a Brick Wall with CGNAT: Most standard internet plans today operate behind CGNAT. The IP address shown on your modem is merely a private IP within the ISP’s metro network (commonly starting with 100.64.0.0/10). You cannot forward ports on ISP-managed hardware unless you pay extra for an expensive static IP plan.
  • Overwhelming Gateway NAT Tables: Small-office routers usually have limited NAT session memory (typically 30,000 to 50,000 concurrent sessions). When hit by automated botnet port sweeps, the session table quickly overflows, causing the entire office network to grind to a halt.

Three Common Alternatives and Their Practical Limits

Before moving to Cloudflare, I evaluated several conventional solutions:

  1. Port Forwarding + DDNS: Fine for personal homelabs. Its weaknesses include exposing your origin IP, complete failure under CGNAT, and forcing your internal servers to absorb the full impact of DDoS attacks.
  2. Internal VPN (WireGuard / OpenVPN): Highly secure for remote employees needing access to internal resources. However, you cannot expect clients to install a VPN client just to review a web staging demo. This approach also fails to receive public third-party webhooks.
  3. Renting a VPS as an Intermediary Reverse Proxy (SSH Tunnel / FRP / Ngrok): I once set up a reverse SSH tunnel to a $5/month VPS in Singapore. While this bypassed CGNAT, it created a single point of failure. Bandwidth was capped by the VPS plan, and if the VPS experienced network degradation, all traffic back to the office collapsed with it.

The Optimal Solution: Deploying Cloudflare Tunnel (cloudflared)

After six months of rock-solid production performance, Cloudflare Tunnel has proven to be the superior choice. The cloudflared daemon running on your internal server proactively establishes an outbound connection to Cloudflare’s Anycast infrastructure via HTTP/2 or QUIC (UDP port 7844). You never need to open a single inbound port on your router.

Internet visitors connect through Cloudflare’s Edge network. As a result, your setup automatically benefits from CDN caching, Web Application Firewall (WAF) filtering, and DDoS mitigation before traffic is securely tunneled to your internal server.

1. Prerequisites

  • A Linux server (Ubuntu 22.04/24.04, Debian 12, Rocky Linux, etc.) running a web service (e.g., Nginx listening on 127.0.0.1:8080).
  • A domain name with its nameservers delegated to Cloudflare (the Free plan works perfectly).

2. Installing cloudflared on Linux

Download the official package for the x86_64 (amd64) architecture on Ubuntu/Debian:

# Download the latest deb package
curl -L --output cloudflared.deb https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-amd64.deb

# Install it onto the system
sudo dpkg -i cloudflared.deb

# Verify the installed version
cloudflared --version

3. Authenticating with Cloudflare

Run the login command to authorize the connection between your server and Cloudflare account:

cloudflared tunnel login

The terminal will print an authentication URL. Copy and paste this link into your browser, log in to your Cloudflare account, and select the domain you wish to authorize. Once authenticated, your browser will close the session and the credentials file cert.pem will be downloaded to ~/.cloudflared/.

4. Creating a New Tunnel

Create an identifiable tunnel for your internal server cluster:

cloudflared tunnel create office-tunnel

The system will generate a JSON credentials file named with your tunnel’s UUID (for example, d41d8cd9-8f00-4b68-96aa-000000000000.json) inside ~/.cloudflared/. Note down this UUID string for the configuration step.

5. Writing the Ingress Rules Configuration File

Create a configuration file at ~/.cloudflared/config.yml:

nano ~/.cloudflared/config.yml

Add your routing rules (make sure to replace the UUID and domain name with your own):

tunnel: d41d8cd9-8f00-4b68-96aa-000000000000
credentials-file: /etc/cloudflared/d41d8cd9-8f00-4b68-96aa-000000000000.json

ingress:
  # Route 1: Forward the primary web app to local port 8080
  - hostname: app.yourdomain.com
    service: http://127.0.0.1:8080

  # Route 2: Forward the monitoring dashboard to port 3000
  - hostname: monitor.yourdomain.com
    service: http://127.0.0.1:3000

  # Catch-all rule: Return 404 for any requests that do not match a hostname
  - service: http_status:404

6. Routing DNS for Subdomains

Automatically create CNAME DNS records pointing your subdomains to the newly created tunnel:

cloudflared tunnel route dns office-tunnel app.yourdomain.com
cloudflared tunnel route dns office-tunnel monitor.yourdomain.com

This command automatically provisions CNAME records pointing to <UUID>.cfargotunnel.com in Cloudflare DNS. You do not need to log into the web dashboard to add them manually.

7. Testing and Configuring the Systemd Service

Test the tunnel directly in your terminal:

cloudflared --config ~/.cloudflared/config.yml tunnel run office-tunnel

Using a smartphone on cellular data (4G/5G), browse to https://app.yourdomain.com. The page should load immediately with a valid HTTPS certificate automatically provisioned by Cloudflare.

Once connectivity is verified, set up cloudflared as a system daemon so it starts automatically on boot:

# Move configuration and credential files to standard system locations
sudo mkdir -p /etc/cloudflared
sudo cp ~/.cloudflared/config.yml /etc/cloudflared/
sudo cp ~/.cloudflared/*.json /etc/cloudflared/

# Install cloudflared as a system service
sudo cloudflared service install

# Enable and start the service
sudo systemctl daemon-reload
sudo systemctl enable cloudflared
sudo systemctl start cloudflared

# Check service status
sudo systemctl status cloudflared

Practical Lessons from Six Months in Production

After more than six months of running this setup in our production environment, here are the three biggest takeaways:

  • Cloudflare Access (Zero Trust) Integration: For sensitive endpoints like monitor.yourdomain.com, you can easily enable a Cloudflare Access policy. Users must authenticate via an email OTP or sign in with Google Workspace before reaching the dashboard, eliminating the need to write custom authentication code for internal utilities.
  • Zero Inbound Ports on the Router: You can completely close all inbound ports on your router and gateway firewalls. With the router dedicated solely to internal LAN traffic, CPU utilization stays comfortably below 15%, with zero risk of botnet port scans or NAT connection table exhaustion.
  • Automatic Self-Healing and Reconnection: Whenever our office WAN IP changes or the connection blips for a few seconds, cloudflared automatically renegotiates the tunnel with the nearest Anycast PoP within 2 to 3 seconds. The recovery happens entirely behind the scenes with no manual intervention required.
Share: