Cloudflare Tunnel: Secure Access Without Public IPs
Invalid Date
A practical guide to setting up Cloudflare Tunnel with PM2 for persistent service management
Cloudflare Tunnel
Cloudflare Tunnel provides a secure way to connect your local services to the internet without exposing a public IP address. Using the cloudflared daemon, you can create outbound-only connections to Cloudflare's global network.
Installation
Install cloudflared using your preferred package manager:
macOS
brew install cloudflaredLinux (Debian/Ubuntu)
wget https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-amd64.deb
sudo dpkg -i cloudflared-linux-amd64.debWindows
Download the latest release from the cloudflared releases page.
Resources
Quick Setup
1. Authenticate with Cloudflare
cloudflared tunnel loginThis opens a browser window to authorize cloudflared with your Cloudflare account.
2. Create a Tunnel
cloudflared tunnel create my-tunnelThis creates a tunnel named "my-tunnel" and generates credentials in ~/.cloudflared/.
3. Configure the Tunnel
Create a configuration file at ~/.cloudflared/config.yml:
tunnel: my-tunnel
credentials-file: /home/user/.cloudflared/<tunnel-id>.json
ingress:
- hostname: app.example.com
service: http://localhost:3000
- hostname: api.example.com
service: http://localhost:8080
- service: http_status:4044. Route DNS to the Tunnel
cloudflared tunnel route dns my-tunnel app.example.com
cloudflared tunnel route dns my-tunnel api.example.comRunning with PM2
To ensure your tunnel stays running persistently, manage it with PM2. Add to your ecosystem.config.js:
module.exports = {
apps: [
{
name: "cloudflare-tunnel",
script: "cloudflared",
args: "tunnel run my-tunnel",
autorestart: true,
restart_delay: 5000,
},
],
};Start the Tunnel
pm2 start ecosystem.config.jsRestart the Tunnel
pm2 restart cloudflare-tunnelStop the Tunnel
pm2 stop cloudflare-tunnelDelete from PM2
pm2 delete cloudflare-tunnelPersist Configuration
Save PM2 process list and enable startup on boot:
pm2 save
pm2 startupKey Benefits
- No Public IP Required: Access services behind NAT or firewalls
- Zero Trust Security: Built-in DDoS protection and access control
- Multiple Services: Route multiple domains through a single tunnel
- Automatic Failover: PM2 ensures the tunnel restarts on failure
Useful Commands
Cloudflared Commands
# List all tunnels
cloudflared tunnel list
# Get tunnel info
cloudflared tunnel info my-tunnel
# Delete a tunnel
cloudflared tunnel delete my-tunnel
# Clean up unused tunnels
cloudflared tunnel cleanup my-tunnelPM2 Commands
# Check tunnel status
pm2 status cloudflare-tunnel
# View tunnel logs
pm2 logs cloudflare-tunnel
# Monitor in real-time
pm2 monit
# Reload configuration
pm2 reload ecosystem.config.js