
Publishing services from home: Cloudflare Tunnel and dynamic DNS
DevOpsNetworkingHomeLabCloudflareCloudflare TunnelDDNSDNSHomeLab
How to publish homelab websites without opening ports using Cloudflare Tunnel, and how to keep a DNS record up to date when your public IP changes with a safe home-made DDNS.
Contents
Publishing a website from home has two classic problems: opening ports on the router, and a public IP that changes when you least expect it. Cloudflare Tunnel solves the first without opening any port, and a small dynamic DNS script solves the second for the cases where you do need the real IP. This guide explains how I use both in my homelab and the mistakes worth avoiding.
Diagram generated with Claude.
How a tunnel works
Normally, for someone to reach your server, the router has to let traffic in. With a tunnel it is the other way round: a program on your server, cloudflared, opens an outbound connection to Cloudflare and keeps it open. Visitors arrive at Cloudflare, which forwards their traffic through that connection.
In practice, the advantages are:
- No open ports on the router.
- Your home IP does not appear in the DNS of the published sites.
- It works behind CGNAT or with a changing IP.
- Cloudflare provides the HTTPS certificate at the edge.
The cost is that traffic goes through Cloudflare, and the tunnel only serves HTTP(S) and a few other specific protocols. It is not the tool for everything, as we will see with the VPN.
Creating the tunnel
The easiest way is from the Cloudflare dashboard, under Zero Trust → Networks → Tunnels. When you create one, it gives you an install command with a token. On a Debian or Ubuntu machine it looks like this:
# Install cloudflared from Cloudflare's repository and register it as a service
sudo cloudflared service install <TUNNEL-TOKEN>
That command creates a systemd unit. You can also write it yourself, which I prefer because it makes clear what runs:
[Unit]
Description=Cloudflare Tunnel
After=network-online.target
Wants=network-online.target
[Service]
ExecStart=/usr/bin/cloudflared --no-autoupdate tunnel run --token <TUNNEL-TOKEN>
Restart=on-failure
RestartSec=5
[Install]
WantedBy=multi-user.target
The token is a secret: it gives control over the tunnel. It goes on that line or in a file with restricted permissions, and never in a repository.
Where the routes live
With a token-managed tunnel, the routes (which domain goes to which local service) are configured in the Cloudflare dashboard, not in a file on the server. In the tunnel’s public routes tab you add entries like:
| Hostname | Service |
|---|---|
app.example.dev | http://localhost:8080 |
panel.example.dev | http://localhost:8090 |
This confuses people who used tunnels with a config.yml file before. If you have that file and start with --token, the file is not used: you can edit it all day with no effect. If for some reason you need both, option order matters: global options go before run, for example tunnel --config <path> run --token ….
Maintenance
sudo systemctl status cloudflared
sudo journalctl -u cloudflared -n 50 --no-pager
cloudflared --version
Two decisions I made:
- I start with
--no-autoupdate. The auto-updater does not fit a systemd service, so I update manually withsudo apt install --only-upgrade cloudflared. - I keep the default protocol, which is QUIC. If your network blocks it, the tunnel will not connect and you will see connection errors in the journal.
And to make a service reachable only through the tunnel, publish it on 127.0.0.1, as we saw in A firewall that really filters with Docker.
What a tunnel does not do well
Not everything fits in a tunnel. My case: the VPN. Headscale (the open-source implementation of Tailscale’s control plane) uses the Noise protocol over a connection upgraded from HTTP, and it works badly through this kind of tunnel. For that I need the name to point to the real home IP, and that is where dynamic DNS comes in.
Nor does it work to create an A record with Cloudflare’s proxy enabled (the orange cloud) pointing to the home IP: that traffic would reach the router, which may forward port 443 somewhere else, and you would end up serving another machine’s website. For names that need the real IP, the record must be unproxied (grey cloud, “DNS only”).
Dynamic DNS with Cloudflare
If your provider changes your public IP, that A record is left pointing at an old address. A DDNS is a loop that, every few minutes, checks your public IP and updates the record if it changed.
The token, with minimum permissions
Create an API token in Cloudflare with only:
Zone → DNS → EditZone → Zone → Read
And limit it to the zone you will touch. Never use a token with permissions over domain registration, nor the global key: if it leaks, it must not be able to do more than change a zone’s DNS records.
The script
This Python example updates a list of exact names:
import ipaddress, os, time, requests
TOKEN = os.environ["CF_API_TOKEN"]
ZONE = os.environ["CF_ZONE_ID"]
HOSTS = [h.strip() for h in os.environ["CF_HOSTS"].split(",")]
POLL = int(os.environ.get("POLL", "300"))
DRY_RUN = os.environ.get("DRY_RUN") == "1"
API = f"https://api.cloudflare.com/client/v4/zones/{ZONE}/dns_records"
HEAD = {"Authorization": f"Bearer {TOKEN}"}
def public_ip():
ip = requests.get("https://api.ipify.org", timeout=10).text.strip()
ipaddress.IPv4Address(ip) # raises ValueError if it is not a valid IPv4 address
return ip
def update(host, ip):
r = requests.get(API, headers=HEAD, params={"type": "A", "name": host}, timeout=10)
r.raise_for_status()
records = r.json()["result"]
if not records:
print(f"{host}: record does not exist, not creating it")
return
rec = records[0]
if rec["content"] == ip:
return
print(f"{host}: {rec['content']} -> {ip}")
if DRY_RUN:
return
data = {"type": "A", "name": host, "content": ip, "ttl": 300, "proxied": False}
r = requests.put(f"{API}/{rec['id']}", headers=HEAD, json=data, timeout=10)
r.raise_for_status()
while True:
try:
ip = public_ip()
for h in HOSTS:
update(h, ip)
except Exception as e:
print("error:", e)
time.sleep(POLL)
There are deliberate decisions in this script:
- Allow-list of exact names (
CF_HOSTS). It only touches the hosts you tell it. My first version updated everyArecord in a zone, and it would have overwritten the root-domain record that pointed to Vercel. - It does not create missing records. If a name does not exist, it says so and moves on. Creating records automatically is a source of surprises.
proxiedalwaysFalse, because these are the names that need the real IP.DRY_RUNmode to see what it would do without changing anything.- It validates what it receives: it discards a response that is not an IPv4 address and fails visibly if Cloudflare answers with an error, instead of assuming an update that never happened.
It also has limits, which I cover below: it does not retry, it does not alert on failures and it relies on an external service to learn your IP.
As a container
services:
ddns:
image: python:3-slim
restart: unless-stopped
command: sh -c "pip install -q requests && python /app/ddns.py"
env_file: .env
volumes:
- ./ddns.py:/app/ddns.py:ro
And the .env, which is never committed to any repository:
CF_API_TOKEN=...
CF_ZONE_ID=...
CF_HOSTS=vpn.example.dev,other.example.dev
POLL=300
When you change the .env, docker compose restart is not enough: the variables are read when the container is created, so it has to be recreated:
docker compose up -d --force-recreate
A real incident
Once my IP changed and one name kept the old address. The script was working fine: that host simply was not in CF_HOSTS. If something does not update, check in this order:
- That the name is in the list, spelled exactly the same.
- That the record exists in Cloudflare and is of type
A. - That the token has both permissions and belongs to that zone.
- The container logs:
docker compose logs --tail 50 ddns.
To see what the network really sees:
dig +short vpn.example.dev @1.1.1.1
curl -s https://api.ipify.org
Both IPs must match.
Limits of this setup
Everything above is designed for a homelab, and it is worth being clear about where it falls short:
- You depend on Cloudflare. Traffic goes through their network and the routes live in their dashboard. If there is an incident or the plan terms change, whatever you have published goes down with them.
- A single
cloudflaredis a single point of failure. If the process or the machine goes down, everything published through that tunnel stops responding. Cloudflare allows running replicas of the same tunnel on different machines, but this guide does not set them up. - There is no monitoring. Nothing described here tells you when the tunnel or the DDNS stops working: you would find out when someone told you.
- The DDNS has a window of error. Between an IP change and the next check, up to five minutes plus the record’s TTL go by with the name pointing at an old address. It also relies on an external service (
api.ipify.org) to learn the IP. That is acceptable for a home VPN and not for anything that needs availability. - The DNS token is a secret with write permission over the zone, and in this setup it lives in a plain-text
.env. Minimum permissions reduce the damage if it leaks; they do not prevent it. - Everything is managed by hand. Tunnel routes and DNS records are changed in the dashboard, with no review and no change history.
What I would change in a professional environment
- Infrastructure as code. Define the tunnel, its routes and the DNS records with Terraform (a Cloudflare provider exists), so changes are reviewable, reproducible and kept in a history.
- A secrets manager instead of a
.env, with periodic token rotation. - High availability and monitoring. Tunnel replicas on more than one machine and an external uptime monitor that alerts by email or messaging when a site stops responding.
- Access control in front of internal dashboards, for example with Cloudflare Access, rather than relying on nobody knowing the address.
- A more robust DDNS: retries, an alert when the update fails and, if your provider offers it, a static IP that makes the DDNS unnecessary.
A tunnel does not replace patching: the nginx2root case
In November 2026 five nginx vulnerabilities were published that can be chained into unauthenticated remote code execution (Xint’s analysis). The most serious, CVE-2026-123007, affects HTTP/2 flow control and does not require nginx to act as a proxy: having HTTP/2 enabled on a publicly reachable listen is enough. According to that analysis it affects versions 1.9.5 through 1.31.8. According to nginx.org’s news page, the fix arrived on 18 November 2026 in versions 1.30.7 (stable) and 1.31.9 (mainline). On Ubuntu or Debian, check whether your package includes the fix as a backport, because the version number may not change.
What changes when you use a tunnel:
- What helps. Cloudflare terminates HTTP/2 and HTTP/3 at its edge, so in principle an attacker does not speak those protocols directly to your nginx. That should close the paths that depend on sending it HTTP/2 or QUIC frames.
- What it does not cover. Unproxied names (grey cloud) pointing at your real IP, like the VPN’s: if there is an nginx with HTTP/2 on port 443 behind it, it is directly exposed. It also does not cover the paths that depend on configuration rather than protocol, such as a
proxy_passwith request variables combined withresolverandmirror, nor an nginx exposed some other way. - The nginx is still vulnerable inside until you update it. The tunnel only lowers the chance that someone reaches it.
What I would do:
- Identify which nginx instances are directly exposed: open router ports and unproxied names.
- On those, disable HTTP/2 and HTTP/3 until patched:
http2 off;on nginx 1.25.1 or later, and removequicfrom thelistendirectives. - Update to a fixed version (1.30.7, 1.31.9 or later) or to a distribution package that includes the patch, and restart nginx: a
reloaddoes not close the old worker processes. - Keep publishing on
127.0.0.1everything that should only be seen through the tunnel.
Summary
- A tunnel opens an outbound connection: no ports, no exposed IP, but only for the traffic it supports.
- With
--token, the routes are in the Cloudflare dashboard; aconfig.ymlhas no effect. - Whatever needs the real IP goes in an unproxied record, and a DDNS keeps it up to date.
- API token with minimum permissions, an allow-list of names and
DRY_RUNfor testing. - It is a homelab setup: a single point of failure, no monitoring and secrets in a
.env. In production: Terraform, a secrets manager, replicas and alerts. - A tunnel reduces exposure but does not replace patching: whatever is published with a real IP stays exposed to vulnerabilities like nginx2root.
Next steps
I solve remote access to the whole home network with my own VPN, and I describe it in a future guide.
Copyright: CC BY-NC-ND 4.0 · José Ángel Alejo Sillero