Deploy a Local LLM, Part 2: Exposing It Safely with a Tunnel or Port Forwarding
Deploy a Local LLM, Part 2: Exposing It Safely with a Tunnel or Port Forwarding
Search
Ask the AI

Deploy a Local LLM, Part 2: Exposing It Safely with a Tunnel or Port Forwarding

This is part two of the Local AI Model Deployment series. At the end of part one you had an inference service on 127.0.0.1:8000 — stable and auto-starting, but reachable only from the machine itself. This part exposes it to the internet safely.

You get two complete routes: a Cloudflare tunnel (no inbound ports at all) and direct port forwarding (your own domain and certificate). They suit different situations, and you can run both — I do.

Local LLM deployment series (4 parts): ① Model and engine → ② Exposing it → ③ Clients → ④ Knowledge base RAG. This is part 2.

Decide which route first

Cloudflare tunnel Direct forwarding
Public IP required No Yes, and not CGNAT
Inbound ports required No Router forwarding needed
TLS certificate Handled at the edge You issue and renew it
Latency Depends on tunnel landing PoP Depends on client-to-home path
Attack surface Cloudflare in front Exposed; your rate limits only
Setup complexity Low Medium

First verify that cloudflared can reach Cloudflare, then configure the tunnel. It works without a forwardable public address, but still needs outbound connectivity, DNS, an account and a hosted domain. Direct access needs a reachable address and permitted inbound ports; the table’s CGNAT restriction concerns ordinary IPv4 forwarding. Enable API-key authentication in the inference service for both routes. Cloudflare in front does not replace it.

Step 1: Put nginx in front

Both configurations use nginx to manage rate limits, path restrictions and backend routing in one place. Inference servers may offer some of these functions themselves. The zone declarations below belong in the http context. Authorization passes to the authentication-enabled backend through normal proxy header forwarding.

# Rate limiting exists to contain a leaked key, not to throttle normal use.
# Set it far above real traffic — a translation client fires dozens of
# requests for a single page.
limit_req_zone  $binary_remote_addr zone=llm_api:10m rate=1200r/m;
limit_conn_zone $binary_remote_addr zone=llm_conn:10m;

server {
    listen 127.0.0.1:8444;          # local only; the tunnel fronts it
    server_name your-domain.example;

    client_max_body_size 24m;        # multimodal image uploads

    location /v1/ {
        limit_req  zone=llm_api burst=300 nodelay;
        limit_conn llm_conn 64;

        proxy_pass http://127.0.0.1:8000;
        proxy_http_version 1.1;
        proxy_set_header Host       $host;
        proxy_set_header X-Real-IP  $remote_addr;
        proxy_set_header Connection "";

        # Streaming responses are SSE. Buffering must be off or the whole
        # answer accumulates and arrives at once.
        proxy_buffering off;
        proxy_cache off;
        proxy_request_buffering off;
        proxy_read_timeout 900s;
        proxy_send_timeout 900s;
    }

    # /metrics exposes prompt length distributions — keep it private
    location = /metrics { return 404; }

    location = /healthz { return 200 "ok\n"; }

    location / { return 404; }
}

The preserved comments describe the original configuration. Rate limits also control normal bursts and overload, so choose rate, burst and queue budgets from capacity. Without trusted real-IP restoration, the tunnel’s local HTTP connection makes $binary_remote_addr aggregate all visitors under cloudflared’s local address. limit_conn is not the model’s slot limit. Trust CF-Connecting-IP only on the controlled tunnel ingress, with a separate trust configuration for direct access.

Three things people get wrong here:

  • Do not omit proxy_buffering off. The symptom is that streaming turns into “long wait, then the whole answer at once” — which looks like a slow model but is nginx accumulating.
  • Set timeouts for the expected output interval. The default proxy_read_timeout is 60 seconds between reads from the upstream. A response that keeps sending data can run longer than 60 seconds.
  • nginx -t passing does not mean the config is live. You must systemctl reload nginx. I have made this mistake more than once.

Route A: Cloudflare tunnel

The machine opens an outbound connection to Cloudflare, and inbound requests arrive through it. No public IP, no inbound ports, no certificate management.

A.1 Install cloudflared

The official apt repository is more reliable than pulling binaries from GitHub:

curl -fsSL https://pkg.cloudflare.com/cloudflare-main.gpg \
  | sudo tee /usr/share/keyrings/cloudflare-main.gpg >/dev/null
echo "deb [signed-by=/usr/share/keyrings/cloudflare-main.gpg] https://pkg.cloudflare.com/cloudflared any main" \
  | sudo tee /etc/apt/sources.list.d/cloudflared.list
sudo apt-get update && sudo apt-get install -y cloudflared
cloudflared --version

Check which cloudflared afterwards. If you previously downloaded a binary by hand, the copy in /usr/local/bin shadows the apt one. A truncated leftover binary cost me an hour: the service segfaulted instantly with no useful diagnostic.

A.2 Create the tunnel

Two credential models with very different blast radius:

Option 1: account credentials on the host (simple)

cloudflared tunnel login          # browser authorization
cloudflared tunnel create my-llm
cloudflared tunnel route dns my-llm llm.your-domain.example

~/.cloudflared/cert.pem grants account-level tunnel management: creating, deleting and managing tunnels, plus DNS routing within its authorized scope. Keeping only the single-tunnel JSON credential on the serving host reduces the permissions exposed by a credential leak.

Option 2: single-tunnel credentials only (recommended)

Create the tunnel and DNS record on a machine that already has credentials, then transfer only that tunnel’s credential file:

# On the machine holding cert.pem
cloudflared tunnel create my-llm
# note the UUID from the output

# Bind DNS — both arguments below matter
printf '' > /tmp/empty.yml
cloudflared tunnel --config /tmp/empty.yml route dns --overwrite-dns <UUID> llm.your-domain.example

Here an empty --config and explicit UUID isolate existing configuration and avoid the config.yml tunnel: selection confusion encountered during this deployment. They are safeguards for this procedure, not requirements for every CLI version. Check that the resulting CNAME points to the intended UUID. --overwrite-dns overwrites an existing record, so verify the hostname first.

Then move the credential without writing the key to an intermediate file:

cat ~/.cloudflared/<UUID>.json \
  | ssh target-host 'mkdir -p ~/.cloudflared && cat > ~/.cloudflared/<UUID>.json && chmod 400 ~/.cloudflared/<UUID>.json'

A.3 Ingress configuration

~/.cloudflared/config.yml:

tunnel: <UUID>
credentials-file: /home/youruser/.cloudflared/<UUID>.json

protocol: quic
retries: 5
grace-period: 30s

ingress:
  - hostname: llm.your-domain.example
    service: http://127.0.0.1:8444        # the nginx layer above
    originRequest:
      connectTimeout: 30s
      keepAliveTimeout: 900s              # do not cut long answers
      httpHostHeader: llm.your-domain.example
  - service: http_status:404              # catch-all

The preserved keepAliveTimeout: 900s setting controls retention of idle keepalive connections. Its original comment incorrectly describes a long-answer timeout. Check cloudflared, edge, nginx and client read/write timeouts separately.

Validate before starting:

cloudflared tunnel --config ~/.cloudflared/config.yml ingress validate
cloudflared tunnel --config ~/.cloudflared/config.yml ingress rule https://llm.your-domain.example/v1/models

A.4 Run it as a service

[Unit]
Description=Cloudflare Tunnel - LLM gateway
After=network.target nginx.service

[Service]
Type=simple
User=youruser
# Use the resolved path — apt installs to /usr/bin, manual installs to /usr/local/bin
ExecStart=/usr/bin/cloudflared tunnel --config /home/youruser/.cloudflared/config.yml run
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target
sudo systemctl daemon-reload && sudo systemctl enable --now cloudflared-llm
sudo journalctl -u cloudflared-llm -n 20 --no-pager | grep "Registered tunnel connection"

Registered tunnel connection shows that the connector registered with the edge. Request the public hostname next to verify DNS, ingress and the backend. A new registration after datagram manager encountered a failure shows recovery; frequent reconnects or failed requests still require a comparison of connection and request logs over the same time window.

A.5 DNS settings

Keep the orange cloud (proxy) enabled. Tunnel traffic must traverse the Cloudflare edge; switching to DNS-only breaks it. This is the exact opposite of the DDNS requirement below, which is easy to mix up.

A.6 Verify

curl -sS -o /dev/null -w "HTTP %{http_code}\n" https://llm.your-domain.example/healthz

Long periods without an upstream response can trigger an edge read timeout. The original 100-second cap on total request duration was inaccurate. At this review, Cloudflare documents a default Proxy Read Timeout of 125 seconds; check the tunnel’s origin settings separately. Use stream: true and verify that data actually reaches the client promptly. Streaming still faces first-chunk delays, later idle intervals and timeouts at other layers.

Route B: Direct port forwarding

Tunnel latency depends on where the tunnel lands. If that PoP is far from both you and your clients, every request takes a long detour. Direct forwarding can be dramatically faster.

B.1 Check three things first

# 1. What is your public IP, and is it CGNAT?
curl -4 -s https://1.1.1.1/cdn-cgi/trace | grep '^ip='

The command reports the egress address seen by a public echo service. It cannot rule out CGNAT, which also presents a routable public exit. Compare the router’s WAN address with that exit and check upstream NAT. A WAN address in 100.64.0.0/10 indicates shared address space; without an upstream mapping, ordinary inbound IPv4 forwarding is unavailable. Alternatives include a tunnel, an ISP-provided public address or verified reachable IPv6.

# 2. Which ports are actually reachable (probe from outside, not locally)
ssh some-vps 'for p in 80 443 8443 9443 9999; do
  timeout 6 nc -z -w 5 YOUR_PUBLIC_IP $p 2>/dev/null && echo "  $p open" || echo "  $p closed"
done'

Always include a control port that should be closed (9999 above). If the control also reports “open”, your probe method is broken and the whole reading is worthless.

Many residential ISPs filter inbound 80/443, so plan on a non-standard port.

# 3. Is this machine's default gateway the router doing NAT?
ip route show default

If forwarding is configured correctly but connections still fail, check the return path described below.

B.2 Dynamic DNS

Residential IPs change, so you need DDNS. Any tool works; the configuration details matter:

  • Publish only an A record. Skip AAAA unless you have verified inbound IPv6 actually works — plenty of setups have addresses but no reachability.
  • Do not detect IPv6 with an echo service. If your machine’s egress goes through a proxy or tunnel, the echo service reports the exit node’s address, and you publish a completely wrong AAAA that is very hard to notice.
  • Use DNS-only for this direct example. Clients must reach the public address on port 9443. DDNS can also update an orange-cloud origin address, but the ordinary Cloudflare HTTP proxy supports only listed ports, which do not include 9443.

B.3 Certificate

With port 80 filtered, HTTP-01 is unavailable. This example uses DNS-01; TLS-ALPN-01 is another option when port 443 is reachable and the client supports it. Install certbot and its dns-cloudflare plugin first, and create a root-readable-only credentials file with a DNS API token scoped to the target zone:

sudo certbot certonly --non-interactive --agree-tos \
  --dns-cloudflare --dns-cloudflare-credentials /root/.secrets/cloudflare.ini \
  --dns-cloudflare-propagation-seconds 30 \
  -d llm-direct.your-domain.example

If the machine issuing the certificate is not the one serving traffic (a reasonable choice if you would rather not put a DNS token on an internet-facing box), add a renewal hook that syncs it:

# In [renewalparams] of /etc/letsencrypt/renewal/<domain>.conf:
# renew_hook = /usr/local/bin/sync-cert.sh

# sync-cert.sh: root reads the cert, a normal user ships it,
# and the private key never lands in an intermediate file
SRC=/etc/letsencrypt/live/<domain>
ssh_peer() { sudo -u relayuser ssh -o BatchMode=yes target-host "$@"; }

ssh_peer "sudo tee /etc/llm/tls/fullchain.pem >/dev/null" < "$SRC/fullchain.pem"
ssh_peer "sudo tee /etc/llm/tls/privkey.pem  >/dev/null && sudo chmod 600 /etc/llm/tls/privkey.pem" < "$SRC/privkey.pem"
ssh_peer "sudo nginx -t && sudo systemctl reload nginx"

The preserved sync script illustrates the transfer sequence. It overwrites the two files separately and does not stop every subsequent step on failure. For deployment, transfer them to a restricted temporary directory, verify the certificate/key pair and nginx configuration, then switch them atomically. Keep the old pair and stop reload if synchronization fails. A Certbot deploy hook can run this process after successful renewal.

B.4 The public-facing nginx site

Different from the internal layer: this one binds all interfaces, terminates TLS, and exposes only API paths:

server {
    # http2 goes on the listen line — the standalone `http2 on;` directive
    # only exists from nginx 1.25.1; older versions fail to start
    listen 9443 ssl http2;
    server_name llm-direct.your-domain.example;

    ssl_certificate     /etc/llm/tls/fullchain.pem;
    ssl_certificate_key /etc/llm/tls/privkey.pem;
    ssl_protocols       TLSv1.2 TLSv1.3;

    # Deliberately no real_ip_header here.
    # The tunnel path needs CF-Connecting-IP to recover the visitor IP;
    # on this path $remote_addr is already the real client, and copying
    # that config would let anyone forge a header to bypass rate limits.

    location /v1/ {
        limit_req  zone=llm_api burst=300 nodelay;
        proxy_pass http://127.0.0.1:8000;
        proxy_http_version 1.1;
        proxy_set_header Host       $host;
        proxy_set_header X-Real-IP  $remote_addr;
        proxy_set_header Connection "";
        proxy_buffering off;
        proxy_request_buffering off;
        proxy_read_timeout 900s;
    }

    location = /healthz { return 200 "ok\n"; }
    location / { return 404; }
}

B.5 Router forwarding

Add one rule: external port → this machine’s LAN IP and port, protocol TCP.

B.6 When forwarding is correct but nothing connects

This is where direct forwarding most often stalls, and it deserves its own section.

Symptom: every setting is right, the service is listening, firewalls are off, and external clients still cannot connect. A packet capture shows something bizarre:

sudo tcpdump -i any -nn "tcp port 9443 and not host 127.0.0.1" -c 20
<client> > <host>:9443    Flags [S]     ← SYN arrives
<host>:9443 > <client>    Flags [S.]    ← SYN-ACK is sent
<client> > <host>:9443    Flags [S]     ← client keeps retransmitting
<client> > <host>:9443    Flags [S]

In this case, captures confirmed that the default gateway differed from the DNAT router. Replies left through a LAN proxy device, bypassing the return NAT mapping for the incoming connection. The router already had incoming connection-tracking state; the return route was wrong. Other failures can produce the same SYN/SYN-ACK pattern, so inspect the actual egress before applying this fix.

The fix is conntrack marking plus policy routing, so replies return the way they came:

IFACE=your-nic      ROUTER=192.168.1.1     PORT=9443
MARK=0x9443         TABLE=100              LAN=192.168.1.0/24
ROUTER_MAC=xx:xx:xx:xx:xx:xx

# 1. External requests: source outside the LAN
iptables -t mangle -A PREROUTING -i "$IFACE" ! -s "$LAN" \
  -p tcp --dport "$PORT" -m conntrack --ctstate NEW \
  -j CONNMARK --set-mark "$MARK"

# 2. NAT hairpin: a LAN device using the public hostname still has a LAN
#    source IP, but it did arrive via the router's DNAT — identify it by
#    the router's source MAC
iptables -t mangle -A PREROUTING -i "$IFACE" \
  -m mac --mac-source "$ROUTER_MAC" \
  -p tcp --dport "$PORT" -m conntrack --ctstate NEW \
  -j CONNMARK --set-mark "$MARK"

# 3. Restore the mark onto subsequent packets, including the SYN-ACK
iptables -t mangle -A PREROUTING -i "$IFACE" -j CONNMARK --restore-mark
iptables -t mangle -A OUTPUT -j CONNMARK --restore-mark

# 4. Marked packets consult a table whose default route is the router
ip route replace "$LAN" dev "$IFACE" scope link table "$TABLE"
ip route replace default via "$ROUTER" dev "$IFACE" table "$TABLE"
ip rule add fwmark "$MARK" lookup "$TABLE"

Three details that will bite:

  • --restore-mark belongs to the CONNMARK target, not the connmark match. Writing -m connmark --restore-mark fails with unknown option.
  • Rule 1’s ! -s $LAN keeps its match limited to external sources. The original deployment sent LAN replies through a table containing only a default route and timed out. This page’s code now includes a connected LAN route, so omitting the exclusion no longer implies that every LAN reply must fail. Check the intended match scope for the actual topology.
  • Rule 2 covers hairpin traffic in this topology. On the same layer-2 network, the router’s source MAC identifies the previous hop; other NAT, bridge and IPv6 paths need separate checks. After the original serial improvement, four concurrent hairpin requests still gave 3/4 successes. Pinning the hostname to the LAN IP gave 4/4 at home; eight external requests gave 8/8.

Install this as a systemd unit (Type=oneshot with RemainAfterExit=yes) rather than running it once — ip rule and iptables do not survive a reboot.

Choosing: a measured comparison

The same system and the same request, measured from two locations:

Vantage point Tunnel Direct
Home network (client in-country) 4.49s 2.61s
Overseas server 0.46s 6.9s (occasional 40s timeout)

The conclusions are opposite. That overseas machine happens to sit beside the tunnel’s landing PoP, so the tunnel is a local hop for it; meanwhile reaching a residential connection from abroad crosses international links that are slow and unreliable.

The choice depends on where my client is. Configure both routes and switch according to the situation.

Three traps when measuring latency

Exclude these sources of interference when measuring latency:

  1. Proxy software on the measuring machine that routes by domain. It can change egress and return paths. The access log shows the server’s last visible peer, which will usually differ from the client’s LAN address after NAT. Compare it with the expected exit, routing and captures. curl --interface <physical-nic> binds an interface; bypassing TUN still depends on system settings.
  2. Testing NAT hairpin from a machine at home. That path behaves nothing like the real external path, especially under concurrency.
  3. Load-testing concurrency from a machine running a proxy. I measured 5/20 concurrent requests succeeding locally while a clean server hit the same backend 20/20 at the same moment — the bottleneck was the test client.

Verification checklist

# Work outward layer by layer so a break is obvious
curl -s 127.0.0.1:8000/health                        # 1. inference server
curl -s 127.0.0.1:8444/healthz                       # 2. inner nginx
curl -s https://llm.your-domain.example/healthz      # 3. tunnel
curl -sk https://llm-direct.your-domain.example:9443/healthz   # 4. direct

# Test all three auth states, and test them from outside
curl -o /dev/null -w "%{http_code}\n" -X POST https://.../v1/chat/completions -d '{}'   # expect 401
curl -o /dev/null -w "%{http_code}\n" -H 'Authorization: Bearer wrong' ...              # expect 401
curl -o /dev/null -w "%{http_code}\n" -H "Authorization: Bearer $KEY" ...               # expect 200

Test authentication on every public path, keeping local tests as controls. I once made a forwarding layer substitute the server’s own key when Authorization was absent, creating an unauthenticated route. Local tests using only valid keys missed it too. Test no key, a wrong key and a valid key on the same path. The curl -sk example is a connectivity diagnostic; remove -k to validate the real certificate.

Next

Your service is now reachable from anywhere. Part three covers wiring it into daily tools — browser translation extensions, code editors, and your own clients — including a technique that cuts token usage by 90%.

Leave a Reply

Scroll down