Every self-hoster eventually hits the same wall. You started with Ollama running locally, added Open WebUI for chat, then bolted on an OpenAI key for the occasional hard question, and maybe an Anthropic key for coding. Now your scripts import three different SDKs, your API keys are scattered across four .env files, and switching models means editing code.
LiteLLM collapses that mess into a single endpoint. It is an open-source proxy that speaks the OpenAI API format and forwards each request to whichever provider you configured — local or hosted. Your application always calls POST /v1/chat/completions; LiteLLM decides where it actually goes.
This guide covers a production-ready Docker deployment, multi-provider routing, virtual API keys, and the cost tracking that makes the whole thing worth running.
Why a gateway instead of direct calls
Before LiteLLM, your code looked like this:
# Different SDK, different auth, different response shape each time
openai_client.chat.completions.create(model="gpt-4o-mini", messages=msgs)
ollama_client.chat(model="llama3.2", messages=msgs)
anthropic_client.messages.create(model="claude-3-5-haiku", messages=msgs)
After LiteLLM:
# One client, one shape. The model string picks the backend.
client.chat.completions.create(model="local-llama", messages=msgs)
client.chat.completions.create(model="gpt-4o-mini", messages=msgs)
client.chat.completions.create(model="claude-haiku", messages=msgs)
The practical wins are bigger than refactoring convenience:
- Failover. If your Ollama box is down, LiteLLM retries against a fallback model automatically.
- Budgets. Per-key spend limits stop a runaway script from burning a monthly API budget overnight.
- Logging. Every request and token count lands in one place instead of four dashboards.
- Key isolation. Give each app its own virtual key. Revoke one without touching the others.
- Model aliasing. Your code says
fast-model; you swap what that means in config, no redeploy.
Prerequisites
- Docker and Docker Compose v2 — if you are new to containers, start with Docker basics for the homelab.
- 2 GB RAM for the gateway itself (it is a lightweight proxy, not an inference engine).
- A Postgres database if you want persistent keys and spend logs — optional for a first run.
- Any upstream providers you want to proxy, plus a reverse proxy if you plan to expose it.
Step 1: Compose file and config
Create a directory, then a docker-compose.yml:
services:
litellm:
image: ghcr.io/berriai/litellm:main-stable
ports:
- "127.0.0.1:4000:4000"
environment:
- LITELLM_MASTER_KEY=sk-change-me-to-a-long-random-string
- OPENAI_API_KEY=${OPENAI_API_KEY}
- ANTHROPIC_API_KEY=${ANTHROPIC_API_KEY}
volumes:
- ./config.yaml:/app/config.yaml:ro
command: ["--config", "/app/config.yaml", "--port", "4000"]
extra_hosts:
- "host.docker.internal:host-gateway"
restart: unless-stopped
Two details matter more than they look. Binding to 127.0.0.1:4000 instead of 4000 means the port is not reachable from the network at all — you must go through your reverse proxy. And extra_hosts is what lets the container reach an Ollama instance on the host; without it, Linux resolves host.docker.internal to nothing and every local model call fails.
Now config.yaml:
model_list:
- model_name: local-llama
litellm_params:
model: ollama_chat/llama3.2
api_base: http://host.docker.internal:11434
- model_name: local-embed
litellm_params:
model: ollama/nomic-embed-text
api_base: http://host.docker.internal:11434
- model_name: gpt-4o-mini
litellm_params:
model: gpt-4o-mini
api_key: os.environ/OPENAI_API_KEY
- model_name: claude-haiku
litellm_params:
model: claude-3-5-haiku-20241022
api_key: os.environ/ANTHROPIC_API_KEY
litellm_settings:
drop_params: true
num_retries: 2
request_timeout: 600
router_settings:
fallbacks:
- local-llama: ["gpt-4o-mini"]
drop_params: true quietly strips parameters a provider does not support instead of erroring — essential once you start switching models behind a fixed client. The fallbacks block is the reliability payoff: if the local box is unreachable, requests land on a hosted model instead of failing.
Start it:
docker compose up -d
docker compose logs -f litellm
Step 2: Verify from the command line
Always test before wiring an app to it:
curl -s http://127.0.0.1:4000/v1/chat/completions \
-H "Authorization: Bearer sk-change-me-to-a-long-random-string" \
-H "Content-Type: application/json" \
-d '{
"model": "local-llama",
"messages": [{"role": "user", "content": "Say hello in five words."}]
}'
Swap "model" for "claude-haiku" and you should get an answer from a completely different backend with no other change. That is the whole point of the exercise.
Step 3: Point existing apps at it
LiteLLM is OpenAI-compatible, so most tools just need a base URL change.
from openai import OpenAI
client = OpenAI(
base_url="http://127.0.0.1:4000/v1",
api_key="sk-change-me-to-a-long-random-string",
)
r = client.chat.completions.create(
model="local-llama",
messages=[{"role": "user", "content": "Summarise the case for self-hosting."}],
)
print(r.choices[0].message.content)
Open WebUI has a “OpenAI-compatible” connection type in its admin settings — paste the gateway URL and the master key, and every model in model_list appears in the UI dropdown. n8n’s OpenAI node works the same way, which means multi-step AI workflows can mix a free local model for cheap steps with a hosted model for the hard ones, all through one credential.
Step 4: Virtual keys and spend limits
Handing every app the master key defeats the purpose. Create scoped keys through the admin UI at http://localhost:4000/ui, or the API:
curl -s http://127.0.0.1:4000/key/generate \
-H "Authorization: Bearer sk-change-me-to-a-long-random-string" \
-H "Content-Type: application/json" \
-d '{
"key_alias": "blog-scripts",
"max_budget": 5.00,
"budget_duration": "30d",
"models": ["gpt-4o-mini", "local-llama"]
}'
The returned sk-... key can only touch those two models and stops working at $5. If a script goes haywire, delete the key and nothing else breaks. Spending caps are the single most useful guardrail in this entire setup — far more valuable than any dashboard.
Step 5: Secure it
The gateway holds every API key you own, so treat it as a secrets store:
- Never bind to
0.0.0.0. Loopback plus reverse proxy, always. - Use a long master key.
openssl rand -hex 32, stored in an environment file or your secrets manager — never committed. - Prefer Tailscale over public exposure. For a home setup there is no reason for this service on the open internet.
- Set
store_model_in_db: falseunless you actually need the UI to hold provider keys, and keep provider keys in environment variables instead.
If you do expose it, put Caddy in front with basic_auth and TLS, and read the homelab security rules once — the failure mode here is a leaked master key, which means someone else spending your credits.
Common problems and fixes
Connection refused on local models. Almost always host.docker.internal not resolving. Confirm Ollama listens on 0.0.0.0:11434 and not just 127.0.0.1, then check extra_hosts.
Provider rejects an unknown parameter. Set drop_params: true. You lose per-provider tuning, gain uniform behaviour.
Streaming stops mid-response. Usually a reverse proxy buffering the response. Disable buffering for the route (flush_interval -1 in nginx, or flush handling in Caddy).
Token counts look wrong. Local models report usage inconsistently. Set custom_tokenizer per model, or accept approximate numbers for Ollama.
Install fails to build a Postgres connection. Set DATABASE_URL or disable the DB-backed features; store_model_in_db: false avoids the dependency for a single-user setup.
Is it worth the extra hop?
Latency is the honest cost: one extra network hop adds a few milliseconds, irrelevant against inference time. In exchange you get a single credential, automatic fallback, per-app budgets and one log stream. For a homelab running two models, it is mild over-engineering. For anything with three or more backends — or any setup where a script could accidentally burn money — it pays for itself immediately.
Start with the compose file above, add your local model first, verify with curl, then move hosted keys behind virtual API keys. Once your application code never mentions a provider name again, you will not want to go back.