Three teams are pulling against three different LLM providers from three different codebases. The data team has hard-coded an OpenAI key into a Jupyter notebook. The product team has the Anthropic key in a Vercel environment variable that nobody can rotate without a deploy. The internal tools team is using a local Ollama instance directly. Your finance lead asks for last month’s LLM spend split by team and gets back three CSVs in three different formats. Then somebody leaves the OpenAI key in a public GitHub commit and you spend a weekend rotating keys, finding the leaked one in five places, and explaining to the same finance lead why you cannot retroactively cap what the leaked key spent.
What’s happening
A LiteLLM proxy fixes this class of problems by becoming the single point of egress for every LLM call your organization makes. Application code talks to LiteLLM over the OpenAI API shape; LiteLLM routes the request to the right upstream (OpenAI, Anthropic, Bedrock, Vertex, local Ollama, vLLM, anything that speaks the LiteLLM provider matrix), applies per-key budgets, records token-level usage in a Postgres database, and returns the response in the OpenAI shape regardless of upstream. The proxy needs PostgreSQL for budgets, virtual keys, and request logs — SQLite is fine for a laptop demo and bad for anything else because budget decrements race under concurrent requests. The master key controls admin operations and creates virtual keys for teams. Virtual keys can have hard limits (tokens, requests, upstream-billing caps), soft limits with alerts, model whitelists, and rate limits. The proxy should not expose its admin UI on the public internet; expose only the /v1/* endpoints publicly and keep /ui and /health/readiness behind your VPN or an authenticated nginx location block. Upstream API keys are environment-variable secrets on the proxy host; rotating them is one place to rotate, not five.
How to verify
After install, the host should expose only :443 and :22:
ss -lntp | grep -E ':(80|443|4000|5432)\b'
# 0.0.0.0:443 nginx
# 127.0.0.1:4000 litellm (via compose)
PostgreSQL on 5432 and the LiteLLM container on 4000 must not appear on the host’s external interfaces. The OpenAI-compatible endpoint must reject requests without a virtual key:
curl -sS -o /dev/null -w '%{http_code}\n' https://llm.example.com/v1/models
# 401 (without Authorization)
A request with a valid virtual key should return the model list:
curl -sS -H "Authorization: Bearer sk-team-data-xxx" \
https://llm.example.com/v1/models | jq '.data[].id'
A chat completion routed through the proxy should reach the upstream and return a usage block:
curl -sS -H "Authorization: Bearer sk-team-data-xxx" \
-H "Content-Type: application/json" \
https://llm.example.com/v1/chat/completions \
-d '{"model":"gpt-4o-mini","messages":[{"role":"user","content":"ping"}]}' \
| jq '.usage'
If .usage is missing or shows zero, the proxy is bypassing the upstream or the model is misnamed in your config.yaml. If the master key works against /v1/chat/completions but virtual keys do not, the database initialization did not run — check docker compose logs litellm for migration errors.
The fix
Save the script below as /root/setup-litellm-ubuntu22.sh, then run it. It installs LiteLLM on a fresh Ubuntu 22.04 VM via Docker Compose: base update, UFW (SSH + HTTP + HTTPS only), SSH hardening with root key preserved, unattended-upgrades, Docker CE + compose plugin, PostgreSQL kept on the internal compose network, the LiteLLM proxy container with master key and Salt key written to /opt/litellm/.env with chmod 600, nginx terminating TLS with the admin UI bound to a path that returns 403 from outside your office IPs, Let’s Encrypt via the certbot nginx plugin, and a poll loop that waits for :4000 and :443 before declaring success.
#!/usr/bin/env bash
set -euo pipefail
### Ubuntu 22.04 LiteLLM proxy clean VM installer
### Keeps root SSH key login enabled, disables SSH password login
### Enables automatic security updates
### Installs Docker + LiteLLM + PostgreSQL + nginx + Let's Encrypt
### PostgreSQL stays on the internal compose network
### Master key + Salt key persisted; rotating Salt key invalidates every virtual key in flight
### No local backups; assumes VM-level backup
### Reboot remains manual
if [[ "$(id -u)" -ne 0 ]]; then
echo "Run as root."
exit 1
fi
: "${LITELLM_DOMAIN:?Set LITELLM_DOMAIN=llm.example.com}"
: "${LITELLM_EMAIL:?Set LITELLM_EMAIL=ops@example.com for Let's Encrypt}"
: "${LITELLM_ADMIN_CIDR:?Set LITELLM_ADMIN_CIDR=203.0.113.0/24 for /ui access}"
LITELLM_VERSION="${LITELLM_VERSION:-v1.52.5-stable}"
LITELLM_PG_PASSWORD="${LITELLM_PG_PASSWORD:-$(openssl rand -hex 24)}"
LITELLM_MASTER_KEY="${LITELLM_MASTER_KEY:-sk-$(openssl rand -hex 24)}"
LITELLM_SALT_KEY="${LITELLM_SALT_KEY:-sk-$(openssl rand -hex 24)}"
echo
echo "========================================"
echo "LiteLLM Proxy Ubuntu 22.04 Setup"
echo "========================================"
echo
echo "==> Updating base OS"
export DEBIAN_FRONTEND=noninteractive
apt-get update
apt-get -y upgrade
echo "==> Installing base packages"
apt-get -y install \
vim curl wget ca-certificates gnupg2 \
chrony fail2ban unattended-upgrades \
ufw lsof tcpdump dnsutils tar gzip \
iproute2 net-tools openssl jq \
software-properties-common
echo "==> Enabling time sync"
systemctl enable --now chrony
timedatectl set-ntp true
echo "==> Applying kernel/network tuning"
cat > /etc/sysctl.d/99-litellm.conf <<'SYSCTL'
net.core.default_qdisc = fq
net.ipv4.tcp_congestion_control = bbr
net.core.somaxconn = 4096
net.core.netdev_max_backlog = 250000
net.ipv4.tcp_max_syn_backlog = 8192
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_fin_timeout = 15
net.ipv4.ip_local_port_range = 10240 65535
net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.default.accept_redirects = 0
kernel.dmesg_restrict = 1
kernel.kptr_restrict = 2
fs.file-max = 2097152
SYSCTL
modprobe tcp_bbr || true
echo tcp_bbr > /etc/modules-load.d/bbr.conf
sysctl --system
echo "==> Setting file limits"
cat > /etc/security/limits.d/99-litellm.conf <<'LIMITS'
* soft nofile 64000
* hard nofile 64000
root soft nofile 64000
root hard nofile 64000
LIMITS
echo "==> Configuring UFW"
ufw --force reset
ufw default deny incoming
ufw default allow outgoing
ufw allow 22/tcp
ufw allow 80/tcp
ufw allow 443/tcp
ufw --force enable
echo "==> Hardening SSH while keeping root SSH key login enabled"
cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak.$(date +%F-%H%M%S)
set_sshd_option() {
local key="$1"
local value="$2"
if grep -qE "^[#[:space:]]*${key}[[:space:]]+" /etc/ssh/sshd_config; then
sed -i "s|^[#[:space:]]*${key}[[:space:]].*|${key} ${value}|" /etc/ssh/sshd_config
else
echo "${key} ${value}" >> /etc/ssh/sshd_config
fi
}
set_sshd_option PermitRootLogin prohibit-password
set_sshd_option PasswordAuthentication no
set_sshd_option PubkeyAuthentication yes
set_sshd_option KbdInteractiveAuthentication no
set_sshd_option ChallengeResponseAuthentication no
set_sshd_option X11Forwarding no
set_sshd_option ClientAliveInterval 300
set_sshd_option ClientAliveCountMax 2
set_sshd_option MaxAuthTries 4
sshd -t
systemctl restart ssh
echo "==> Configuring fail2ban"
mkdir -p /etc/fail2ban/jail.d
cat > /etc/fail2ban/jail.d/sshd.local <<'FAIL2BAN'
[sshd]
enabled = true
port = ssh
backend = systemd
maxretry = 4
findtime = 10m
bantime = 1h
FAIL2BAN
systemctl enable --now fail2ban
echo "==> Configuring unattended-upgrades"
cat > /etc/apt/apt.conf.d/20auto-upgrades <<'AUTOUPG'
APT::Periodic::Update-Package-Lists "1";
APT::Periodic::Unattended-Upgrade "1";
APT::Periodic::AutocleanInterval "7";
AUTOUPG
echo "==> Installing Docker CE"
install -m 0755 -d /etc/apt/keyrings
curl -fsSL https://download.docker.com/linux/ubuntu/gpg \
| gpg --dearmor -o /etc/apt/keyrings/docker.gpg
chmod a+r /etc/apt/keyrings/docker.gpg
echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/ubuntu jammy stable" \
> /etc/apt/sources.list.d/docker.list
apt-get update
apt-get -y install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
systemctl enable --now docker
echo "==> Preparing /opt/litellm"
mkdir -p /opt/litellm/config
chmod 700 /opt/litellm
cat > /opt/litellm/.env <<ENV
LITELLM_VERSION=${LITELLM_VERSION}
LITELLM_DOMAIN=${LITELLM_DOMAIN}
PG_PASSWORD=${LITELLM_PG_PASSWORD}
LITELLM_MASTER_KEY=${LITELLM_MASTER_KEY}
LITELLM_SALT_KEY=${LITELLM_SALT_KEY}
DATABASE_URL=postgresql://litellm:${LITELLM_PG_PASSWORD}@postgres:5432/litellm
# Upstream provider keys go here. Rotate by editing this file
# and running 'docker compose up -d --force-recreate litellm'.
OPENAI_API_KEY=
ANTHROPIC_API_KEY=
ENV
chmod 600 /opt/litellm/.env
cat > /opt/litellm/config/config.yaml <<'CONFIG'
model_list:
- model_name: gpt-4o-mini
litellm_params:
model: openai/gpt-4o-mini
api_key: os.environ/OPENAI_API_KEY
- model_name: gpt-4o
litellm_params:
model: openai/gpt-4o
api_key: os.environ/OPENAI_API_KEY
- model_name: claude-sonnet-4
litellm_params:
model: anthropic/claude-sonnet-4-20250514
api_key: os.environ/ANTHROPIC_API_KEY
- model_name: claude-haiku
litellm_params:
model: anthropic/claude-haiku-4-20250514
api_key: os.environ/ANTHROPIC_API_KEY
- model_name: local-llama
litellm_params:
model: ollama_chat/llama3.1:8b
api_base: http://host.docker.internal:11434
litellm_settings:
set_verbose: false
drop_params: true
num_retries: 2
request_timeout: 600
telemetry: false
general_settings:
master_key: os.environ/LITELLM_MASTER_KEY
database_url: os.environ/DATABASE_URL
store_model_in_db: true
proxy_batch_write_at: 60
database_connection_pool_limit: 10
ui_access_mode: "admin_only"
router_settings:
routing_strategy: simple-shuffle
enable_pre_call_checks: true
CONFIG
chmod 600 /opt/litellm/config/config.yaml
cat > /opt/litellm/docker-compose.yml <<'COMPOSE'
services:
postgres:
image: postgres:16-alpine
restart: unless-stopped
environment:
POSTGRES_USER: litellm
POSTGRES_PASSWORD: ${PG_PASSWORD}
POSTGRES_DB: litellm
volumes:
- pgdata:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U litellm -d litellm"]
interval: 30s
timeout: 5s
retries: 5
start_period: 20s
litellm:
image: ghcr.io/berriai/litellm:${LITELLM_VERSION}
restart: unless-stopped
depends_on:
postgres:
condition: service_healthy
extra_hosts:
- "host.docker.internal:host-gateway"
environment:
LITELLM_MASTER_KEY: ${LITELLM_MASTER_KEY}
LITELLM_SALT_KEY: ${LITELLM_SALT_KEY}
DATABASE_URL: ${DATABASE_URL}
OPENAI_API_KEY: ${OPENAI_API_KEY}
ANTHROPIC_API_KEY: ${ANTHROPIC_API_KEY}
STORE_MODEL_IN_DB: "true"
DISABLE_ADMIN_UI: "false"
volumes:
- /opt/litellm/config/config.yaml:/app/config.yaml:ro
command: ["--config", "/app/config.yaml", "--port", "4000", "--num_workers", "2"]
ports:
- "127.0.0.1:4000:4000"
ulimits:
nofile:
soft: 64000
hard: 64000
volumes:
pgdata:
driver: local
COMPOSE
echo "==> Starting LiteLLM stack"
docker compose --env-file /opt/litellm/.env -f /opt/litellm/docker-compose.yml up -d
echo "==> Waiting for LiteLLM on 127.0.0.1:4000"
for i in {1..120}; do
if ss -lntp | grep -q '127.0.0.1:4000'; then
break
fi
sleep 2
done
if ! ss -lntp | grep -q '127.0.0.1:4000'; then
echo "LiteLLM failed to listen on 127.0.0.1:4000"
docker compose -f /opt/litellm/docker-compose.yml logs --tail=200 litellm || true
exit 1
fi
echo "==> Installing nginx and certbot"
apt-get -y install nginx certbot python3-certbot-nginx
cat > /etc/nginx/sites-available/litellm <<NGINX
upstream litellm_backend {
server 127.0.0.1:4000;
keepalive 32;
}
server {
listen 80;
listen [::]:80;
server_name ${LITELLM_DOMAIN};
return 301 https://\$host\$request_uri;
}
server {
listen 443 ssl http2;
listen [::]:443 ssl http2;
server_name ${LITELLM_DOMAIN};
client_max_body_size 50M;
proxy_read_timeout 600s;
proxy_send_timeout 600s;
proxy_connect_timeout 60s;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
add_header X-Content-Type-Options nosniff always;
add_header X-Frame-Options SAMEORIGIN always;
add_header Referrer-Policy strict-origin-when-cross-origin always;
# Admin UI restricted to known CIDR
location ~ ^/(ui|sso) {
allow ${LITELLM_ADMIN_CIDR};
deny all;
proxy_set_header Host \$host;
proxy_set_header X-Real-IP \$remote_addr;
proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto \$scheme;
proxy_http_version 1.1;
proxy_pass http://litellm_backend;
}
# Health endpoints restricted to admin CIDR
location ~ ^/health {
allow ${LITELLM_ADMIN_CIDR};
deny all;
proxy_pass http://litellm_backend;
}
# Public OpenAI-compatible endpoints
location / {
proxy_set_header Host \$host;
proxy_set_header X-Real-IP \$remote_addr;
proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto \$scheme;
proxy_http_version 1.1;
proxy_buffering off;
proxy_pass http://litellm_backend;
}
}
NGINX
ln -sf /etc/nginx/sites-available/litellm /etc/nginx/sites-enabled/litellm
rm -f /etc/nginx/sites-enabled/default
nginx -t
systemctl enable --now nginx
systemctl reload nginx
echo "==> Requesting Let's Encrypt certificate"
certbot --nginx --non-interactive --agree-tos \
-m "${LITELLM_EMAIL}" -d "${LITELLM_DOMAIN}" --redirect
systemctl enable --now certbot.timer
echo "==> Waiting for HTTPS listener"
for i in {1..30}; do
if ss -lntp | grep -q ':443'; then
break
fi
sleep 1
done
echo "==> Final package update"
apt-get -y upgrade
echo
echo "========================================"
echo "DONE"
echo "========================================"
echo
echo "Kernel:"
uname -r
echo
echo "Listeners:"
ss -lntp | grep -E ':(80|443|4000|5432)\b' || true
echo
echo "Containers:"
docker compose -f /opt/litellm/docker-compose.yml ps
echo
echo "Public endpoint check (expect 401 without bearer):"
curl -sS -o /dev/null -w '%{http_code}\n' "https://${LITELLM_DOMAIN}/v1/models" || true
echo
echo "Master key check:"
curl -sS -H "Authorization: Bearer ${LITELLM_MASTER_KEY}" \
"https://${LITELLM_DOMAIN}/v1/models" -o /dev/null -w '%{http_code}\n' || true
echo
echo "Secrets written to /opt/litellm/.env (mode 600). Move to your secrets manager and remove from this host before going live."
echo "LITELLM_SALT_KEY MUST be persisted across redeploys. Rotating it invalidates every virtual key in flight."
echo
echo "Master key: ${LITELLM_MASTER_KEY}"
echo "Admin UI: https://${LITELLM_DOMAIN}/ui (restricted to ${LITELLM_ADMIN_CIDR})"
echo "Public API: https://${LITELLM_DOMAIN}/v1/*"
echo
echo "First steps:"
echo "1. Edit /opt/litellm/.env and set OPENAI_API_KEY / ANTHROPIC_API_KEY."
echo "2. docker compose -f /opt/litellm/docker-compose.yml up -d --force-recreate litellm"
echo "3. Open https://${LITELLM_DOMAIN}/ui from the admin CIDR. Sign in with the master key."
echo "4. Create one Team per consuming team. Create one Virtual Key per app under each Team."
echo "5. Set max_budget (USD upstream billing) and tpm/rpm caps on each virtual key."
echo "6. Application code uses base_url=https://${LITELLM_DOMAIN}/v1 with the virtual key as the bearer token."
Make it executable and run it:
chmod 700 /root/setup-litellm-ubuntu22.sh
LITELLM_DOMAIN=llm.example.com \
LITELLM_EMAIL=ops@example.com \
LITELLM_ADMIN_CIDR=203.0.113.0/24 \
/root/setup-litellm-ubuntu22.sh
Open https://llm.example.com/ui from the admin CIDR. Sign in with the master key. Create a Team per consuming team (data, product, internal-tools). Under each Team, create one Virtual Key per application — that way you can revoke a single app’s key without breaking the rest. Set max_budget on each virtual key as the cap on upstream billing that key is allowed to incur over its rotation window; LiteLLM blocks calls that would exceed the budget. Application code uses base_url=https://llm.example.com/v1 with the virtual key as the bearer. Spend reports come out of the Postgres database by team, by key, by model, by day — one source of truth, not three CSVs.
Run the proxy on Stack Harbor’s managed cloud compute with patching, monitoring, and Sev-1 escalation in place: Cloud compute. For full environment-level operations including key rotation playbooks and budget alerting, see Managed Cloud Ops.