This assumes you have a free Cloudflare account and you're already using it as your DNS provider. Also, this is going to be using cloudflared
directly on-demand, rather than an always-on systemd service. Based on the official tutorial.
Installing the system service is optional.
# mac
brew install cloudflared
# linux
curl -fsSLo cloudflared.deb https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-amd64.deb
sudo dpkg -i cloudflared.deb
Run this and click the link in your terminal. If you have multiple domains (origins), you'll be prompted to choose one.
cloudflared login
Click the Authorize
button to proceed. This creates ~/.cloudflared/cert.pem
. As long as that exists, you're logged in.
This creates ~/.cloudflared/<UUID>.json
and prints the UUID so you can copy it:
cloudflared tunnel create tun
If you go to one.dash.cloudflare.com and click "Tunnels", you'll see your tunnel and its UUID with a status of Inactive
.
Now store the UUID in a variable:
uuid=<YOUR_UUID>
And run this to inject the tunnel ID into ~/.cloudflared/config.yml
:
cat <<EOF | tee ~/.cloudflared/config.yml > /dev/null
url: http://localhost:8000
tunnel: $uuid
credentials-file: $HOME/.cloudflared/$uuid.json
EOF
The config file can support multiple tunnels. You can also just use a single tunnel and change the port number in the config as needed.
You can run cloudflared tunnel list
to view all your tunnels and cloudflared tunnel info <id|name>
for details on a tunnel.
This creates the CNAME record for your subdomain. Replace tun.example.com
with your own:
cloudflared tunnel route dns tun tun.example.com
Go to dash.cloudflare.com and click "DNS Records". You should see the new CNAME
record with the content being the UUID of the tunnel.
First run an app:
cd tmp
touch index.html
echo "<h1>Hello, world!</h1>" > index.html
python -m http.server
Now run the tunnel (in a new terminal):
cloudflared tunnel run tun
Go to tun.example.com and you should see your running app!
If you go back to the Zero Trust Dashboard and click "Tunnels", you should see your tunnel with a status of Healthy
.
To stop the tunnel, simply Ctrl+C in the terminal where it's running. Back in the dashboard, you should see the status change to Down
.
Delete your tunnel, create a new tunnel, and overwrite your DNS record:
cloudflared tunnel delete tun
cloudflared tunnel create tun
cloudflared tunnel route dns -f tun tun.example.com
Then recreate ~/.cloudflared/config.yml
with the new tunnel UUID.