Somebody is probably scanning your server right now. Public IPs get probed constantly, and an LLM endpoint is a juicy target because every request burns your GPU or your API bill. The usual fix is a firewall full of exceptions. There is a quieter option: close every inbound port and let the server dial out to Cloudflare instead. We built a small FastAPI gateway with keys, logging and rate limits, tested it, and wired it to a tunnel. Here is the whole recipe, including what we could not verify.
Key takeaways
- Outbound Only: cloudflared dials out to Cloudflare, so the host can block all inbound traffic. Cloudflare's docs ask only for egress on port 7844.
- Two Locks, Not One: Cloudflare Access service tokens gate the hostname, and per-client API keys in the gateway give you names, limits and revocation.
- Tested Gateway: Our 56-line gateway rejected missing and wrong keys with 401, rate limited the fourth call with 429 and streamed tokens through unbuffered.
- The 100-Second Trap: Cloudflare cuts requests that send no byte for about 100 to 125 seconds. Stream completions or they die with a 524.
Why Open Ports Are the Wrong Default for LLM Servers
An open port is an invitation that anyone can accept. Ollama and vLLM ship with no authentication, so a port forwarded to them hands strangers free inference. Closing every inbound port removes the whole class of problem, because there is nothing to scan, brute force or fingerprint.
The usual workaround is a reverse proxy, a firewall rule per client IP and a pile of fail2ban config. It works until a laptop changes networks or a rule gets forgotten. A tunnel flips the direction instead. Your server starts the connection, so the firewall can stay shut. The trade is that you now depend on Cloudflare being up, and that every request passes through their network.
Think of it like a mail slot versus a front door. A front door needs a lock, a doorbell and a peephole. A mail slot in a wall with no door on your side needs none of that, because nobody can walk in from the street.
How Cloudflare Tunnel Works Without Inbound Ports
cloudflared is a small daemon that makes outbound-only connections to Cloudflare, so the server needs no publicly routable IP. Cloudflare's firewall guidance says to block all ingress and allow egress on port 7844, over TCP and UDP, to the regional connect hosts.
The daemon keeps several persistent connections open, and Cloudflare routes requests for your hostname down them. According to Cloudflare's docs, the connect hosts are region1.v2.argotunnel.com and region2.v2.argotunnel.com. You can test the path from the server with nc -uvz -w 3 IP 7844 against one of their addresses.
One limit surprised us. Cloudflare documents that Authenticated Origin Pulls does not apply to tunnel hostnames, so you cannot lean on mutual TLS to the origin as a second lock. That is part of why the gateway checks its own keys.
The Gateway: Auth, Logging and Rate Limits in 56 Lines
The gateway sits between the tunnel and your model server. It checks a bearer key, applies a per-client rate limit, forwards the body untouched and logs one JSON line per request. It does not log prompts or answers, only the client name, status, size and latency.
import hmac, json, os, time, logging from collections import defaultdict, deque import httpx from fastapi import FastAPI, Header, HTTPException, Request from fastapi.responses import JSONResponse, StreamingResponse UPSTREAM = os.environ.get("UPSTREAM", "http://127.0.0.1:11434") API_KEYS = {k: n for n, k in (p.split(":", 1) for p in os.environ["GATEWAY_KEYS"].split(","))} LIMIT, WINDOW = int(os.environ.get("RATE_LIMIT", "30")), 60 log = logging.getLogger("gateway") logging.basicConfig(level=logging.INFO, format="%(message)s") app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None) hits = defaultdict(deque) client = httpx.AsyncClient(base_url=UPSTREAM, timeout=httpx.Timeout(120.0, connect=5.0)) def who(authorization: str | None) -> str: token = (authorization or "").removeprefix("Bearer ").strip() for key, name in API_KEYS.items(): if hmac.compare_digest(token.encode(), key.encode()): return name raise HTTPException(401, "invalid api key") @app.get("/healthz") async def healthz(): return {"ok": True} @app.post("/v1/chat/completions") async def chat(request: Request, authorization: str | None = Header(None)): name = who(authorization) now = time.monotonic() q = hits[name] while q and now - q[0] > WINDOW: q.popleft() if len(q) >= LIMIT: raise HTTPException(429, "rate limit exceeded") q.append(now) body = await request.body() start = time.monotonic() req = client.build_request("POST", "/v1/chat/completions", content=body, headers={"content-type": "application/json"}) upstream = await client.send(req, stream=True) async def stream(): try: async for chunk in upstream.aiter_raw(): yield chunk finally: await upstream.aclose() log.info(json.dumps({"key": name, "status": upstream.status_code, "bytes_in": len(body), "ms": round((time.monotonic() - start) * 1000)})) return StreamingResponse(stream(), status_code=upstream.status_code, media_type=upstream.headers.get("content-type")) A few choices are deliberate. Keys are compared with hmac.compare_digest, so timing does not leak how many characters matched. The interactive docs and OpenAPI routes are switched off, because a public docs page is free reconnaissance. And the upstream response is streamed chunk by chunk, which matters for the timeout problem later.
The limiter is a sliding window held in process memory. That is fine for one worker and one machine. If you run several workers, each keeps its own count, so move the counters to Redis before you trust the numbers.
What We Tested, and What We Could Not
The gateway passed every check we threw at it locally, but we could not test a live tunnel. We ran it on Python 3.10 with fastapi 0.162.5, httpx 0.29.0 and uvicorn 0.54.0, against a fake upstream that streams four tokens. With the limit set to 3 per minute, the results matched what the code promises.
| Request | Result |
|---|---|
| No Authorization header | 401 |
| Wrong key | 401 |
| Valid key, streaming | 200, tokens arrive as separate events |
| Same key, calls 2 and 3 | 200 and 200 |
| Same key, call 4 inside the minute | 429 |
| Second client, own key | 200, limits are per client |
| GET /docs | 404 |
The log lines held only the client name, status, request size and milliseconds. We also bound the gateway to 127.0.0.1 and tried to connect to the machine's other address on the same port. The connection was refused, which is the property the tunnel design relies on.
Here is what we did not test: a real Cloudflare tunnel. We had no Cloudflare account wired to this sandbox, so every tunnel and Access step below comes from Cloudflare's documentation, not from our own run. The scan commands later are there so you can check your own server rather than trust ours.
Wiring the Tunnel With Docker Compose
Create a remotely managed tunnel in the Cloudflare dashboard, copy its token, and run cloudflared next to the gateway. Cloudflare says anyone holding the token can run the tunnel, so keep it in an env file and never commit it.
In the dashboard, go to Networking, then Tunnels, then Create Tunnel, and add a public hostname such as llm.example.com that points to http://gateway:8000. Inside a Compose network the service name resolves, so the gateway never needs a published port.
services: gateway: build: . environment: GATEWAY_KEYS: "${GATEWAY_KEYS}" UPSTREAM: "http://host.docker.internal:11434" extra_hosts: ["host.docker.internal:host-gateway"] # no "ports:" section on purpose. Nothing is published to the host. cloudflared: image: cloudflare/cloudflared:latest command: tunnel --no-autoupdate run --token ${TUNNEL_TOKEN} depends_on: [gateway] The gateway needs a small Dockerfile that runs uvicorn gateway:app --host 0.0.0.0 --port 8000. The 0.0.0.0 is safe here because the container port is not published to the host, and only cloudflared shares its network. If you run without Docker, bind to 127.0.0.1 instead.
Then close the host. On Ubuntu with ufw, deny incoming and allow outgoing. Remember to allow SSH from your own address first, or move SSH behind the tunnel too, or you will lock yourself out.
sudo ufw default deny incoming sudo ufw default allow outgoing sudo ufw enable sudo ufw status verbose Adding Cloudflare Access Service Tokens as the First Lock
Cloudflare Access can refuse requests before they ever reach your server. Create a service token, which is a Client ID and Client Secret pair, then add an Access policy with the Service Auth action that includes that token. Clients send both values as headers.
Per Cloudflare's docs, the path is Zero Trust, Access controls, Service credentials, Service Tokens. Name each token after the client that uses it, so the logs tell you who did what, and set an expiry you will actually remember to rotate. The secret is shown once.
curl https://llm.example.com/v1/chat/completions \ -H "CF-Access-Client-Id: $CF_ID" \ -H "CF-Access-Client-Secret: $CF_SECRET" \ -H "Authorization: Bearer $GATEWAY_KEY" \ -H "content-type: application/json" \ -d '{"model":"llama3.2","messages":[{"role":"user","content":"hi"}],"stream":true}' Notice what this buys you. A scanner that discovers llm.example.com gets stopped at Cloudflare's edge, without touching your server. A leaked gateway key alone is useless without the service token, and the reverse is also true. If you want people to log in with a browser instead, Access supports identity providers too, but machine clients should use tokens.
The 100-Second Trap and Other Tunnel Gotchas
Cloudflare waits roughly 100 to 125 seconds for the origin's first byte, then returns a 524. Its docs give 125 seconds as the default Proxy Read Timeout, and a third-party write-up says the limit is fixed outside Enterprise plans. A slow, non-streaming completion can trip it.
This is the sneaky one for LLM work. A long generation with "stream": false sends nothing until it finishes, which looks identical to a dead server. Setting "stream": true sends the first token quickly and keeps bytes flowing, and the connection never idles long enough to be cut. That is why our gateway passes chunks through instead of buffering the whole answer.
Two more limits to know. Cloudflare support documents a 100 MB request body on Free and Pro plans, so big uploads return a 413. And the tunnel adds a network hop, so expect a little extra latency on the first token compared with a direct connection. We did not measure that, so we will not guess a number.
Put a deadline on your own side too. The gateway's upstream client allows 120 seconds, which is past Cloudflare's limit on purpose, because the edge should be the thing that gives up first and gives you a clean error to debug.
Verify Nothing Is Exposed: The Scan You Should Run
Do not trust the diagram, scan the machine. Run ss -tlnp on the server to see every listening socket, then scan the public IP from a different network with nmap. A correct setup shows no open ports from outside, and the hostname answers only through Cloudflare.
# On the server: what is listening, and on which address? ss -tlnp # From a different machine: is anything answering on the public IP? nmap -Pn -p- --min-rate 2000 YOUR.SERVER.IP # Does the hostname reach the gateway, and is it protected? curl -i https://llm.example.com/healthz On the server, the only sockets that should appear are loopback ones or container ports not published to the host. From outside, every port should read filtered or closed. If nmap shows 22 open, that is SSH, and you decide whether that is acceptable. Our test machine showed the gateway on 127.0.0.1 only, and a connection to its other address was refused.
Then try the hostname without credentials. You should get an Access denial, not your gateway's 401. If you see the gateway's own response, the Access policy is not attached to that hostname yet. For a longer walk through hardening the model server behind this gateway, see our self-hosted LLMs with Ollama guide.
Tunnel, VPN or Port Forward: A Quick Decision Table
Use a tunnel when you serve HTTP clients you do not control, a VPN when only your own devices connect, and a port forward only when you accept the scanning that follows. The right pick depends on who calls the endpoint and how much operating work you want.
| Situation | Pick | Why |
|---|---|---|
| Teammates and apps call your LLM over HTTPS | Cloudflare Tunnel plus Access | No inbound ports, per-client tokens |
| Only your own laptop and phone connect | A private VPN mesh | No public hostname at all |
| Quick demo for an hour | Tunnel with a short-lived token | Easy to tear down |
| Must not depend on a third party | Reverse proxy and a hardened firewall | You own every layer, and every mistake |
If your agents sit behind this gateway, the same keys let you cap what each one can spend. Our guide to LangChain, LangGraph and plain Python agents covers the loop that will be calling it, and the n8n queue mode setup shows another service worth putting behind the same tunnel.
Frequently Asked Questions
Does Cloudflare Tunnel need any open inbound ports?
No. cloudflared opens outbound connections to Cloudflare, so you can block all inbound traffic on the host firewall. Cloudflare's firewall guidance says to allow outbound traffic on port 7844 over TCP and UDP, and nothing inbound. This article could not run a live tunnel, so verify with your own scan.
Is Cloudflare Tunnel free?
The tunnel itself has no separate fee. Cloudflare's Zero Trust Free plan covers teams under 50 users at $0, and the pay-as-you-go plan is $7 per user per month at the time of writing. You still need a domain on Cloudflare to publish a public hostname.
Why do my LLM requests time out with a 524 error?
Cloudflare's proxy waits about 100 to 125 seconds for the origin to send a first byte, and Free, Pro and Business plans cannot change it. A non-streaming completion sends nothing until it finishes. Stream the response, or move long jobs to a background queue.
Do I still need API keys if I use Cloudflare Access?
Yes, treat them as two separate layers. Access decides who may reach the hostname, and the gateway key says which client is calling, so you can log, rate limit and revoke per client. Dropping either layer means one leaked secret is enough.
What is the upload limit through Cloudflare?
Cloudflare support documents a 100 MB request body limit on Free and Pro plans, 200 MB on Business and 500 MB on Enterprise by default. Chat prompts are far smaller, but large document or image uploads to your gateway can hit it and return a 413 error.
Should the gateway log prompts?
Not by default. Our gateway logs the client name, status, request size and latency, and never the prompt or the answer. Prompts often hold customer data and secrets, so log content only when you have a retention policy and a reason.
Can I run this in front of Ollama or vLLM?
Yes. Both expose an OpenAI-style chat completions route, and the gateway forwards the body untouched. Point the UPSTREAM variable at the local address, keep that server bound to 127.0.0.1, and let only the gateway and cloudflared talk to it.
Sources: Cloudflare Tunnel, Access service token, connection limits, error 524 and error 413 documentation (developers.cloudflare.com), Cloudflare Zero Trust plan pricing (cloudflare.com), and our own gateway tests on Python 3.10, fastapi 0.162.5, httpx 0.29.0 and uvicorn 0.54.0, November 2026. The tunnel and Access steps were not run live.
Originally published on aivlyn.com. This is a syndicated copy with a canonical link back to the original.
