⭐ Core project · #5 · part 1 of 3

🤖 Local AI gateway — the private API

Run a private LLM on your home rig: engine + LiteLLM proxy + Tailscale sidecar, all in one Docker stack. The engine never leaves the Docker network; LiteLLM is the only public face, behind a master key. Same architecture you'll keep all the way through parts 2 and 3 — no walk-back as you add a chat UI or multi-user features.

⭐ Core AI/ML Intermediate ~45 min Prereqs: M3 + Docker sidecar (Core #4)

Why this project

Cloud LLM APIs cost money and see your prompts. Local LLMs are free and private — but they need a sane network architecture if you want to reach them safely from anywhere on your tailnet. This project builds that architecture properly the first time, so you don't have to walk it back when you add a chat UI (part 2) or invite friends (part 3).

The shape: engine + LiteLLM + Tailscale sidecar in one Docker stack, on a private internal network. The engine never opens a port on your host. The Tailscale sidecar is the only thing tagged for the tailnet, and it forwards to LiteLLM, which forwards to the engine. Master key gates access. Tailscale ACL gates who can even reach the master-key prompt.

👤Who this helps

  • You already use ChatGPT/Claude/Gemini and want a free, private alternative for the 80% of asks that don't need a frontier model
  • You have a beefy machine at home that's underutilized
  • You want the architecture right the first time, not "expedient now, fix later"
  • You'll plug your tailnet URL into editor extensions (Continue, Aider, Cursor) — and want auth from day one

🎁What you get

  • An Ollama or llama.cpp engine + LiteLLM proxy + Tailscale sidecar — all in one docker compose up
  • An OpenAI-compatible API at https://ai-rig.tail-abc.ts.net, behind a master key
  • Engine bound only to the Docker internal network — never reachable from your host's LAN, never from public IPs, never from any wifi you join
  • Foundation that doesn't change as you layer on the chat UI (part 2) or multi-user features (part 3)

📋Prerequisites

  • Tailscale running on the Docker host (M3)
  • Docker Engine + Compose v2 plugin. Verify with docker compose version. If it errors with "unknown command", see the callout below.
  • Your user in the docker group (sudo usermod -aG docker $USER then newgrp docker)
  • Core #4: Docker sidecar pattern — this project extends that pattern
  • HTTPS Certificates enabled in admin → DNS

Ubuntu / Pop!_OS / Debian gotcha: the system docker.io package ships Docker Engine but not the Compose v2 plugin. docker compose up will fail with "unknown command: docker compose". Fix with sudo apt install docker-compose-v2. (Or use the legacy hyphenated tool: sudo apt install docker-compose and replace docker compose with docker-compose in every command below.)

Mental model

The Docker sidecar pattern from Core #4 with two more containers behind the proxy. The Tailscale sidecar is the only outward-facing piece; everything else is on a private Docker network.

CLIENTS PRIVATE EDGE DOCKER STACK 📜 curl / scriptswith master key 🛠️ editor toolsContinue / Aider / Cursor 🔒 ts-ai sidecar · HTTPS · ts.net hostnamehttps://ai-rig.tail-abc.ts.net · tag:ai PRIVATE DOCKER NETWORK 🔀 LiteLLM proxyport 4000 · OpenAI-compat · master key required 🦙 Ollama / ⚡ llama.cppno host port · only LiteLLM can reach it

The dashed teal box is the Docker bridge network. Nothing inside that box has a port published to your host. The only way in from the tailnet is through the ts-ai sidecar at the top, which speaks HTTPS, and which forwards only to LiteLLM. Part 2 adds Open WebUI on the same private network. Part 3 adds cloud fallback as a config change to LiteLLM.

Engine comparison

Both engines speak OpenAI-compatible APIs, so the rest of the project (and parts 2 and 3) work with either. Default in this project: Ollama; the walkthrough also has a llama.cpp tab.

🦙 Ollama⚡ llama.cpp🚀 vLLM
Audience Self-hosters who want it to "just work" Power users, custom quantizations Production teams serving many users on Nvidia GPUs
Docker image ollama/ollama:latest ghcr.io/ggml-org/llama.cpp:server vllm/vllm-openai:latest
Models ollama pull by name · easy Mount GGUF files from host disk Reference HF models · downloads on first run
Best at Personal use, small homelabs Maximum control, specific quants Continuous batching · multi-user concurrency
API OpenAI-compat (/v1/...) OpenAI-compat OpenAI-compat

Hardware notes

Apple Silicon footnote: Docker Desktop on Mac can't pass Metal through to containers, so Ollama-in-Docker on a Mac runs CPU-only — much slower than native. If you're on Apple Silicon and want Metal, see the "Native engine on Apple Silicon" Variation at the bottom of this page. The compose file in the main path still works on Mac; it'll just be slower than native.

Model size vs hardware tier (Q4_K_M quantization)
Llama 3.2 1B
1.3 GB
Llama 3.2 3B
2.0 GB
Phi-3 Mini 3.8B
2.4 GB
Llama 3.1 8B
4.7 GB
Qwen 2.5 14B
9 GB
Mistral Small 22B
13 GB
Llama 3.3 70B
40 GB
DeepSeek-R1 70B
40 GB
8 GB
16 GB
24 GB
40+ GB

Tier reference: 8 GB ≈ RTX 3070 · 16 GB ≈ Apple Silicon mid · 24 GB ≈ RTX 4090 / M-series Pro · 40+ GB ≈ M3 Max or dual GPU

Steps

Six steps. Declare the tag in your ACL, mint the auth key + master key, write the compose file, bring it up + pull a model, verify from another tailnet device, lock down access with ACLs.

Placeholder note. Throughout these steps you'll see tail-abc.ts.net as a placeholder for your actual tailnet name. Replace it with yours everywhere it appears. To find your tailnet name: admin console → DNS → "Tailnet name" at the top, OR run tailscale status on any tailnet device and look at the suffix on any device row. It's something like tailXXXXXX by default; you can rename it in admin → DNS to something prettier (e.g. your-name.ts.net) any time, but it's purely cosmetic.

Declare tag:ai in your tailnet ACL ~2 min

The Tailscale sidecar will register itself with the tag tag:ai. Tailscale rejects any auth key that uses a tag that isn't declared as owned by some group or user — so do this before minting the auth key, or you'll get a requested tags [tag:ai] are invalid or not permitted error from the sidecar at startup.

Admin console → Access controls. Add or merge:

{
  "tagOwners": {
    "tag:ai": ["autogroup:admin"]
  },
  "acls": [
    // ... your existing rules — don't replace them ...
  ]
}

Save. Tailscale validates the JSON; a successful save means the tag exists. autogroup:admin is fine for a single-admin tailnet (you); use a named group like group:family if you've defined one.

Mint a Tailscale auth key + a LiteLLM master key ~3 min

Two secrets the stack needs:

  • Tailscale auth key — admin console → Settings → Auth keys → Generate. Reusable: off. Ephemeral: off (we want this device to persist). Pre-authorized: on. Tags: pick tag:ai from the tag picker (the option appears now that you declared it in the previous step). Copy the tskey-auth-... string.
  • LiteLLM master key — generate any random string starting with sk-. openssl rand -hex 24 | sed 's/^/sk-/' works.

Save both somewhere temporary; you'll paste them into a .env file in step 3.

Create the project directory + files ~10 min

SSH into your home server and create the project:

mkdir -p ~/local-ai && cd ~/local-ai

1. .env — secrets only, never committed anywhere:

TS_AUTHKEY=tskey-auth-XXXXX
LITELLM_MASTER_KEY=sk-your-random-string

2. litellm-config.yaml — minimal: one model, master key required for any request:

model_list:
  - model_name: llama-3.2-3b
    litellm_params:
      model: ollama/llama3.2:3b
      api_base: http://ollama:11434

litellm_settings:
  num_retries: 2

general_settings:
  master_key: os.environ/LITELLM_MASTER_KEY

3. serve-config.json — Tailscale Serve config, lives inside the ts-ai sidecar; forwards to LiteLLM by Docker service name:

{
  "TCP": { "443": { "HTTPS": true } },
  "Web": {
    "${TS_CERT_DOMAIN}:443": {
      "Handlers": { "/": { "Proxy": "http://litellm:4000" } }
    }
  }
}

4. docker-compose.yml — three services on one private bridge network. The pattern is the same as Core #4 (Docker sidecar), extended to multiple backend services:

services:
  ts-ai:
    image: tailscale/tailscale:latest
    hostname: ai-rig
    environment:
      - TS_AUTHKEY=${TS_AUTHKEY?required}
      - TS_EXTRA_ARGS=--advertise-tags=tag:ai
      - TS_SERVE_CONFIG=/config/serve.json
      - TS_STATE_DIR=/var/lib/tailscale
    volumes:
      - ts-state:/var/lib/tailscale
      - ./serve-config.json:/config/serve.json
      - /dev/net/tun:/dev/net/tun
    cap_add: [net_admin, sys_module]
    restart: unless-stopped
    networks: [ai-net]

  litellm:
    image: ghcr.io/berriai/litellm:main-stable
    command: ["--config", "/app/config.yaml"]
    volumes:
      - ./litellm-config.yaml:/app/config.yaml
    environment:
      - LITELLM_MASTER_KEY=${LITELLM_MASTER_KEY?required}
    restart: unless-stopped
    networks: [ai-net]
    depends_on: [ollama]

  ollama:
    image: ollama/ollama:latest
    volumes:
      - ollama-models:/root/.ollama
    restart: unless-stopped
    networks: [ai-net]
    # GPU passthrough — uncomment for Linux + Nvidia:
    # deploy:
    #   resources:
    #     reservations:
    #       devices:
    #         - { driver: nvidia, count: all, capabilities: [gpu] }

networks:
  ai-net:
    driver: bridge

volumes:
  ts-state:
  ollama-models:

Notice what's missing: there's no ports: stanza on any service. The engine listens on the Docker bridge network only; LiteLLM listens on the bridge only. The only path in is through the ts-ai sidecar, which Tailscale itself handles.

Bring the stack up + pull a model ~5 min · download time varies

docker compose up -d
docker compose logs -f ts-ai
# Watch for these lines (in order) — they mean the sidecar registered:
#   active login: ai-rig.<your-tailnet>.ts.net
#   Switching ipn state Starting -> Running
#   serve: creating a new proxy handler for http://litellm:4000
#   Startup complete, waiting for shutdown signal
# Then Ctrl-C out of the log tail.

# Confirm from any other tailnet device that ai-rig appears in the status:
#   tailscale status | grep ai-rig

# Pull a model into the ollama container:
docker compose exec ollama ollama pull llama3.2:3b

Browse ollama.com/library for more model names. Pull whatever fits your hardware tier; update litellm-config.yaml with new model_name entries as you add them.

Verify from another tailnet device ~3 min

From your laptop or phone (any tailnet device that isn't the engine host), call the API. The master key is required:

curl https://ai-rig.tail-abc.ts.net/v1/chat/completions \
  -H "Authorization: Bearer sk-your-random-string" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "llama-3.2-3b",
    "messages": [{"role":"user","content":"Why is the sky blue?"}]
  }'

Wait a few seconds (first call loads the model into memory), get a JSON response. This is the moment the project pays off. Your home rig is doing the inference; LiteLLM is enforcing the master key; Tailscale Serve is the only public face.

While you're at it, confirm the engine is genuinely not reachable from your LAN:

# From any device on your home LAN that's NOT on the tailnet:
curl http://<your-server-LAN-ip>:11434/api/tags
# Should fail (connection refused / timeout). The engine has no host port.

Lock down the tailnet exposure with ACLs ~3 min

The tag tag:ai was applied to ts-ai when it joined the tailnet. Restrict who can reach it:

{
  "tagOwners": { "tag:ai": ["group:family"] },
  "acls": [
    { "action": "accept", "src": ["group:family"], "dst": ["tag:ai:443"] }
  ]
}

Now even a guest user or a tagged container that's on your tailnet can't reach the API unless they're family. Combined with the master key requirement, you have two independent layers gating access.

Reference

✓Verify

  • curl /v1/models with the master key returns your model list
  • Same call without the Authorization header returns 401
  • Direct connection to the engine port from your LAN (not tailnet) fails — engine has no host port
  • Off-tailnet curl to the tailnet hostname gets nothing

⚠Common issues

  • ts-ai logs say "requested tags [tag:ai] are invalid or not permitted" — you didn't declare tag:ai in tagOwners, or the auth key was minted before the declaration was saved. Add "tag:ai": ["autogroup:admin"] to tagOwners, save, mint a fresh auth key, update .env, then docker compose down && docker compose up -d.
  • ts-ai logs say "auth failed" — auth key wrong, expired, or already consumed (single-use keys register one device only). Mint a fresh one.
  • LiteLLM 401 on every request — master key mismatch. Header is Authorization: Bearer sk-... with no quotes around the value.
  • LiteLLM 503 / "Connection refused" — Ollama hasn't finished starting yet. docker compose logs ollama to confirm; first run downloads the image.
  • "model not found" — you didn't docker compose exec ollama ollama pull <model>. Models live in the container volume and must be pulled explicitly after up.
  • Cert provisioning fails — HTTPS Certificates must be enabled in admin → DNS first.
  • Slow first response — model loads into memory on first call; subsequent requests are fast. Pre-warm by curling once before you need it.
  • Out of memory — model too large for your VRAM/RAM. Pull a smaller variant or quantization.

⚐Caveats

  • Local models lag frontier models on hard reasoning. The 80/20 case is well-served; the 20% isn't. Part 3's cloud fallback handles this gracefully.
  • The master key has full admin rights to LiteLLM. Treat it like a database password — rotate periodically, never commit to a public repo, never share in a chat. Per-user virtual keys come in part 3.
  • Ollama in Docker on Apple Silicon is CPU-only (see the Variation below). Linux + Nvidia GPU is fully supported with the deploy stanza in the compose file.
  • Ollama serializes requests by default — fine for one user, sluggish with multiple. If you'll be sharing, see Part 3's "Choosing an engine" comparison.

Variations

Engine swap · Apple Silicon

Native Ollama for Metal acceleration

Docker Desktop on Mac can't pass Metal through to containers, so the in-container Ollama runs CPU-only. If you're on Apple Silicon and want full Metal speed:

  1. Install Ollama natively from ollama.com/download
  2. Set launchctl setenv OLLAMA_HOST "0.0.0.0:11434" and restart the Ollama app (this opens a 0.0.0.0 bind — see Caveats above before deciding)
  3. Remove the ollama service from docker-compose.yml
  4. Change LiteLLM's api_base from http://ollama:11434 to http://host.docker.internal:11434

Trades the clean "engine bound to Docker network only" architecture for native Metal performance. Worth it for serious local model use on Mac.

Engine swap · all platforms

llama.cpp instead of Ollama

Three coordinated changes — the architecture (sidecar / LiteLLM / Tailscale Serve / ACL) is unchanged, only the engine container and how LiteLLM addresses it differ.

1. Swap the ollama service for llama-cpp:

llama-cpp:
  image: ghcr.io/ggml-org/llama.cpp:server
  # For Nvidia GPU: image: ghcr.io/ggml-org/llama.cpp:server-cuda
  command:
    - "-m"
    - "/models/Meta-Llama-3.1-8B-Instruct-Q4_K_M.gguf"
    - "--host"
    - "0.0.0.0"
    - "--port"
    - "8080"
    - "-c"
    - "4096"
  volumes:
    - ./models:/models
  restart: unless-stopped
  networks: [ai-net]

2. Download a GGUF instead of using ollama pull. llama.cpp loads model files from disk:

mkdir -p ~/local-ai/models && cd ~/local-ai/models
huggingface-cli download \
  bartowski/Meta-Llama-3.1-8B-Instruct-GGUF \
  Meta-Llama-3.1-8B-Instruct-Q4_K_M.gguf \
  --local-dir .
cd ..
docker compose up -d

Browse Hugging Face's GGUF models for more. Q4_K_M is a sensible default quantization; Q5_K_M or Q8_0 for higher fidelity at larger size.

3. Change LiteLLM's model entry from ollama/... to openai/...:

model_list:
  - model_name: llama-3.1-8b
    litellm_params:
      model: openai/llama-3.1-8b      # 'openai/' prefix = OpenAI-compat backend
      api_base: http://llama-cpp:8080
      api_key: dummy                  # llama.cpp doesn't check by default; field still required

The openai/ prefix tells LiteLLM to use the standard OpenAI API shape. llama.cpp's server is OpenAI-compatible at /v1/..., so this routes correctly.

Scaling

One model per llama.cpp process

llama.cpp's server loads one GGUF per container. For multiple models, run multiple llama-cpp services on different ports:

llama-cpp-8b:
  image: ghcr.io/ggml-org/llama.cpp:server
  command: ["-m", "/models/llama-8b.gguf", "--host", "0.0.0.0", "--port", "8080"]
  volumes: [./models:/models]
  networks: [ai-net]

llama-cpp-3b:
  image: ghcr.io/ggml-org/llama.cpp:server
  command: ["-m", "/models/llama-3b.gguf", "--host", "0.0.0.0", "--port", "8081"]
  volumes: [./models:/models]
  networks: [ai-net]

Then add two LiteLLM model_list entries pointing at llama-cpp-8b:8080 and llama-cpp-3b:8081. Ollama avoids this by loading/unloading on the fly inside a single process — a real ergonomic win, even if llama.cpp is faster per-model on tuned setups.

Hardening

API-key auth at the engine (defense in depth)

If you want application-layer auth at the engine itself (in addition to LiteLLM's master key), pass --api-key <key> in llama.cpp's command array. Then update LiteLLM's api_key: to that value. Most readers don't need this — LiteLLM's master/virtual key system already gates access — but it's there if you want defense in depth.

Engine swap · GPU

vLLM for production-style serving

Swap in vllm/vllm-openai with appropriate model args. Same compose pattern; same Tailscale exposure. Practical mostly with Nvidia GPUs. See Part 3's "Choosing an engine" comparison for when this is worth the effort.

Use case

Editor integrations (Continue / Aider / Cursor)

All three accept custom OpenAI-compatible base URLs. Point them at https://ai-rig.tail-abc.ts.net with the master key. Free, private code completion that uses your home rig. Part 3 covers minting per-tool virtual keys so you can rotate independently and revoke without disrupting the others.

Anti-pattern · not recommended

Engine-direct path (skipping LiteLLM)

Technically possible — drop the litellm service from compose, point ts-ai's serve config at http://ollama:11434, and inside the engine container set OLLAMA_HOST=0.0.0.0:11434 as an env to relax the host-header check. You'll lose the per-key auth that LiteLLM gives you for free, and you can't grow into parts 2 and 3 without rebuilding. Not recommended unless you've decided you genuinely never want a proxy.

Where this leads

You have a private, master-key-gated API. Great for scripts and editor extensions. But chatting via curl is awkward — most readers want a real UI for browsing past conversations, switching models, and just talking to the thing. Part 2 adds Open WebUI on the same Docker network without modifying anything you just built — Open WebUI becomes another client of the LiteLLM you already have.

→
Part 2 of 3 · Featured
💬 Local AI: add a chat UI (Open WebUI)
Drop Open WebUI into the same compose file. New tailnet hostname for chat; the API hostname from part 1 keeps working.
›

More natural follow-ups: