
Many apps assume the OpenAI API shape: /v1/chat/completions, bearer tokens, streaming responses, and familiar error codes. You can keep that contract and still run models on your own server.
This tutorial shows how to install an OpenAI compatible API proxy on a VPS. You’ll point it at a local model runtime (Ollama or llama.cpp). You’ll also add API keys, basic rate limiting, and useful access logging.
By the end, you’ll have a single HTTPS endpoint like https://llm-gateway.example.com/v1/chat/completions. Existing apps can call it with no code changes beyond the base URL and API key.
What you’ll build (and what it won’t do)
You’re building a small gateway in front of a self-hosted LLM runtime:
- Nginx terminates HTTPS, enforces an API key, rate-limits callers, and writes access logs.
- Ollama (or llama.cpp server) runs the model locally on your VPS or dedicated server.
- Optional mappings let you keep your app’s model name (
gpt-4o-mini, etc.) while the backend uses a local model (llama3,qwen,mistral).
Honest limitations:
- This isn’t a full OpenAI drop-in for every endpoint. Some clients depend on edge cases (tool calling formats, audio endpoints, embeddings variants) that your local runtime may not support.
- CPU-only inference on a small VPS gets slow fast with larger models. It’s still practical for internal tools, low-traffic assistants, and background jobs.
- Rate limiting here is Nginx-level and IP-based by default. If you need per-user quotas, add an auth layer or a small gateway app.
Infrastructure sizing: pick a VPS or dedicated server that fits
Start with the machine. If you under-provision, everything else looks “broken” even when the config is fine.
- Small CPU-only gateway (recommended for experimentation): 4 vCPU, 8–16 GB RAM. Works for small quantized models and low concurrency.
- Comfortable CPU-only: 8 vCPU, 32 GB RAM. Lower latency and more headroom for larger context windows.
- GPU server (best for real-time chat): Dedicated server with an NVIDIA GPU and enough VRAM for the model size you want. VRAM is the hard limit.
Rules of thumb that hold up in practice:
- RAM still matters on GPU: you need system RAM for runtime overhead, prompt buffers, and concurrency.
- Quantization trades footprint for output quality: smaller quantizations reduce memory use, but can degrade results for some tasks.
- Context size drives memory: longer prompts and larger context windows increase memory pressure and latency.
If you want a simple place to run this, a HostMyCode VPS fits CPU-only gateways and dev environments.
For higher traffic or GPU inference, run the model runtime on a larger box and keep the gateway lightweight.
Prerequisites
- Ubuntu or Debian VPS with root access (or sudo).
- A domain name pointed to your server (A/AAAA record).
- Ports
80and443open to the internet.
If you need help with DNS pointing, HostMyCode domains are at domains.
Put the gateway on its own subdomain (example: llm-gateway.example.com).
Step 1: Install and run a local LLM backend (Ollama)
This guide uses Ollama because it’s easy to operate on a single host. If you prefer llama.cpp, you can switch later. The overall pattern stays the same.
-
Install Ollama as a system service:
curl -fsSL https://ollama.com/install.sh | sh -
Confirm the service is running:
sudo systemctl status ollama --no-pager -
Pull a model. If you’re CPU-only, start smaller than you think you need:
ollama pull llama3 ollama pull qwen2.5Tip: if model sizing is new to you, the notes on quantization and footprint in Quantize Llama models for Ollama on a VPS will save you time.
-
Smoke test locally (Ollama listens on
127.0.0.1:11434by default):curl -s http://127.0.0.1:11434/api/tags | jq
If you want to run llama.cpp instead (often faster for certain CPU workloads), follow: Self-Host llama.cpp Server API on Ubuntu VPS.
Whichever backend you use, keep it private on localhost. Expose only the proxy.
Step 2: Create the OpenAI-compatible gateway service
There are a few ways to build an OpenAI-style gateway:
- a purpose-built “OpenAI compatible proxy” app (more features, more moving parts), or
- Nginx as a thin policy layer + a small translation service.
For a VPS, the second option is usually the least fragile.
Here, a tiny Node.js service translates OpenAI chat requests into Ollama calls. It listens on localhost. Nginx stays public and handles TLS, auth, and limits.
2.1 Install Node.js and create a non-root user
Create a dedicated user for the gateway:
sudo adduser --system --group --home /opt/llm-gateway llm-gateway
Install Node.js from the Debian/Ubuntu repos. This is fine for a small internal service.
If your distro version is too old, use NodeSource. Keep it aligned with your OS patching process.
sudo apt update
sudo apt install -y nodejs npm
Check versions:
node -v
npm -v
2.2 Create the gateway app
Create a working directory:
sudo mkdir -p /opt/llm-gateway/app
sudo chown -R llm-gateway:llm-gateway /opt/llm-gateway
Create /opt/llm-gateway/app/package.json:
{
"name": "llm-openai-gateway",
"version": "1.0.0",
"type": "module",
"dependencies": {
"express": "^4.19.2"
}
}
Install dependencies:
sudo -u llm-gateway npm --prefix /opt/llm-gateway/app install
Create /opt/llm-gateway/app/server.js:
import express from "express";
const app = express();
app.use(express.json({ limit: "2mb" }));
// Configure these via environment variables.
const OLLAMA_URL = process.env.OLLAMA_URL || "http://127.0.0.1:11434";
const DEFAULT_MODEL = process.env.DEFAULT_MODEL || "llama3";
const PORT = parseInt(process.env.PORT || "8088", 10);
// Optional model alias mapping: "gpt-4o-mini=llama3,qwen=qwen2.5"
const MODEL_ALIASES = new Map();
const aliasRaw = process.env.MODEL_ALIASES || "";
for (const pair of aliasRaw.split(",").map(s => s.trim()).filter(Boolean)) {
const [k, v] = pair.split("=").map(s => s.trim());
if (k && v) MODEL_ALIASES.set(k, v);
}
function pickModel(openaiModel) {
if (!openaiModel) return DEFAULT_MODEL;
return MODEL_ALIASES.get(openaiModel) || openaiModel;
}
function messagesToPrompt(messages = []) {
// Simple, predictable formatting. Not perfect, but stable.
// If you need strict role handling or tool calls, extend this.
return messages.map(m => {
const role = (m.role || "user").toUpperCase();
const content = typeof m.content === "string" ? m.content : JSON.stringify(m.content);
return `${role}: ${content}`;
}).join("\n") + "\nASSISTANT:";
}
app.get("/healthz", (req, res) => res.json({ ok: true }));
// Minimal OpenAI-like endpoint
app.post("/v1/chat/completions", async (req, res) => {
try {
const body = req.body || {};
const model = pickModel(body.model);
const prompt = messagesToPrompt(body.messages);
const stream = Boolean(body.stream);
if (stream) {
// Simple streaming via newline-delimited JSON chunks.
// Many OpenAI SDKs expect SSE; if your client needs SSE, implement it.
res.setHeader("Content-Type", "application/json");
res.setHeader("Transfer-Encoding", "chunked");
}
const r = await fetch(`${OLLAMA_URL}/api/generate`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ model, prompt, stream })
});
if (!r.ok) {
const text = await r.text();
return res.status(502).json({ error: { message: text || "Upstream error" } });
}
if (stream) {
const reader = r.body.getReader();
const decoder = new TextDecoder();
let full = "";
while (true) {
const { value, done } = await reader.read();
if (done) break;
const chunk = decoder.decode(value, { stream: true });
// Ollama streams JSON lines; parse line-by-line.
for (const line of chunk.split("\n").filter(Boolean)) {
try {
const obj = JSON.parse(line);
if (obj.response) {
full += obj.response;
res.write(JSON.stringify({ delta: obj.response }) + "\n");
}
} catch {
// Ignore partial lines
}
}
}
res.end();
return;
}
const data = await r.json();
const content = data.response || "";
// Return a compact OpenAI-style payload.
res.json({
id: "chatcmpl-local",
object: "chat.completion",
created: Math.floor(Date.now() / 1000),
model,
choices: [
{
index: 0,
message: { role: "assistant", content },
finish_reason: "stop"
}
]
});
} catch (e) {
res.status(500).json({ error: { message: e?.message || "Internal error" } });
}
});
app.listen(PORT, "127.0.0.1", () => {
console.log(`LLM gateway listening on 127.0.0.1:${PORT}`);
});
This gateway stays intentionally small. It fits many clients that send chat messages and expect one assistant reply.
If your app needs SSE streaming, tool calls, embeddings, or structured outputs, extend the handler. You shouldn’t need to change the infrastructure layout.
2.3 Run it with systemd
Create /etc/systemd/system/llm-gateway.service:
[Unit]
Description=Local OpenAI-style gateway to Ollama
After=network.target ollama.service
[Service]
Type=simple
User=llm-gateway
Group=llm-gateway
WorkingDirectory=/opt/llm-gateway/app
Environment=PORT=8088
Environment=OLLAMA_URL=http://127.0.0.1:11434
Environment=DEFAULT_MODEL=llama3
# Optional: keep your app model name but map it to local models
Environment=MODEL_ALIASES=gpt-4o-mini=llama3,qwen=qwen2.5
ExecStart=/usr/bin/node /opt/llm-gateway/app/server.js
Restart=on-failure
RestartSec=2
# Basic hardening
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=strict
ProtectHome=true
ReadWritePaths=/opt/llm-gateway
[Install]
WantedBy=multi-user.target
Enable and start:
sudo systemctl daemon-reload
sudo systemctl enable --now llm-gateway
sudo systemctl status llm-gateway --no-pager
Test locally:
curl -s http://127.0.0.1:8088/healthz | jq
curl -s http://127.0.0.1:8088/v1/chat/completions \
-H 'Content-Type: application/json' \
-d '{"model":"gpt-4o-mini","messages":[{"role":"user","content":"Say hello in one sentence."}]}' | jq
Step 3: Put Nginx in front (HTTPS, API key, rate limits, logging)
Don’t expose the gateway raw.
Nginx handles the parts you still need in production: TLS, header hygiene, rate limiting, and access logs you can use while debugging.
3.1 Install Nginx and Certbot
sudo apt update
sudo apt install -y nginx certbot python3-certbot-nginx
Create an Nginx server block for llm-gateway.example.com (replace domain):
sudo nano /etc/nginx/sites-available/llm-gateway
Paste this (HTTP only for now; Certbot will upgrade it):
limit_req_zone $binary_remote_addr zone=llm_ratelimit:10m rate=10r/s;
limit_conn_zone $binary_remote_addr zone=llm_connlimit:10m;
server {
listen 80;
server_name llm-gateway.example.com;
access_log /var/log/nginx/llm-gateway.access.log;
error_log /var/log/nginx/llm-gateway.error.log;
location /.well-known/acme-challenge/ { root /var/www/html; }
location / {
return 301 https://$host$request_uri;
}
}
Enable the site:
sudo ln -s /etc/nginx/sites-available/llm-gateway /etc/nginx/sites-enabled/llm-gateway
sudo nginx -t
sudo systemctl reload nginx
Get a certificate:
sudo certbot --nginx -d llm-gateway.example.com
If you already have a preferred TLS setup, keep it.
If you want a clean baseline for VPS apps, the HTTPS patterns are similar to Traefik With Docker Compose for HTTPS on a VPS. For a single gateway, Nginx is plenty.
3.2 Enforce an API key (Bearer token)
Start with one shared token. If you end up with multiple callers, switch to per-client keys later.
Create a secret token:
openssl rand -hex 32
Edit your Nginx TLS server block (Certbot added it under /etc/nginx/sites-enabled/llm-gateway).
Add these lines inside the server { ... } that listens on 443.
# --- LLM gateway protection ---
# Hard limit concurrency per IP
limit_conn llm_connlimit 20;
# Rate limit requests per IP
limit_req zone=llm_ratelimit burst=20 nodelay;
# Expect Authorization: Bearer <token>
set $llm_required_token "REPLACE_WITH_YOUR_TOKEN";
if ($http_authorization = "") { return 401; }
if ($http_authorization !~* "^Bearer\s+(.+)$") { return 401; }
set $llm_token $1;
if ($llm_token != $llm_required_token) { return 403; }
# Reduce accidental exposure
add_header X-Content-Type-Options nosniff always;
add_header X-Frame-Options DENY always;
add_header Referrer-Policy no-referrer always;
# Log upstream timings for troubleshooting
log_format llm '$remote_addr - $time_iso8601 "$request" $status '
'rt=$request_time urt=$upstream_response_time '
'ua="$http_user_agent"';
access_log /var/log/nginx/llm-gateway.access.log llm;
Then add a reverse proxy location to forward OpenAI paths to your local gateway:
location /v1/ {
proxy_pass http://127.0.0.1:8088;
proxy_http_version 1.1;
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;
# Streaming-friendly defaults
proxy_buffering off;
proxy_read_timeout 300;
}
location = /healthz {
proxy_pass http://127.0.0.1:8088/healthz;
}
Reload Nginx:
sudo nginx -t
sudo systemctl reload nginx
Test from your laptop:
export LLM_URL="https://llm-gateway.example.com"
export LLM_KEY="REPLACE_WITH_YOUR_TOKEN"
curl -s "$LLM_URL/v1/chat/completions" \
-H "Authorization: Bearer $LLM_KEY" \
-H 'Content-Type: application/json' \
-d '{"model":"gpt-4o-mini","messages":[{"role":"user","content":"Give me two nginx hardening tips."}]}' | jq
Step 4: Point an existing OpenAI client at your proxy
This is the payoff for using an OpenAI-compatible endpoint. Most apps and SDKs don’t need a redesign.
Example: curl-compatible OpenAI call
curl -s "$LLM_URL/v1/chat/completions" \
-H "Authorization: Bearer $LLM_KEY" \
-H 'Content-Type: application/json' \
-d '{
"model": "gpt-4o-mini",
"messages": [
{"role":"system","content":"You are concise."},
{"role":"user","content":"Write a 1-paragraph maintenance window notice."}
]
}' | jq -r '.choices[0].message.content'
Example: set environment variables for apps
Many frameworks respect these variables:
export OPENAI_BASE_URL="https://llm-gateway.example.com/v1"
export OPENAI_API_KEY="REPLACE_WITH_YOUR_TOKEN"
If your library uses OPENAI_API_BASE or similar, set the equivalent.
What matters is that your app sends the bearer token Nginx expects.
Step 5: Practical logging and troubleshooting
Most failures are boring: wrong model name, backend not running, timeouts, or rate limiting.
Check logs first. Then change config.
5.1 Check Nginx access logs for timing
sudo tail -n 50 /var/log/nginx/llm-gateway.access.log
Look for:
rt=request time: how long your caller waited.urt=upstream response time: how long the gateway waited on Ollama.
5.2 Check the gateway service logs
sudo journalctl -u llm-gateway -n 200 --no-pager
5.3 Validate the backend directly
curl -s http://127.0.0.1:11434/api/generate \
-H 'Content-Type: application/json' \
-d '{"model":"llama3","prompt":"Say OK"}' | jq
Common failures (quick fixes)
- 403 from Nginx: the bearer token doesn’t match. Recheck
$llm_required_token. - 429 too many requests: your rate limit is too strict. Increase
rate=and/orburst=. - 502 bad gateway: the Node gateway isn’t running, or it can’t reach Ollama. Check systemd logs.
- Slow responses: CPU-only inference + large model. Use a smaller/quantized model, reduce context, or move inference to a bigger server.
If your VPS runs out of disk because of model downloads or logs, follow: Disk Full on VPS: Find Large Files and Free Space Safely.
Step 6: Security hardening that matters for an AI endpoint
An AI gateway is still an API. The usual problems show up quickly: leaked credentials, prompt abuse, and surprise load. Here, “surprise load” often means surprise CPU burn.
- Keep the backend private: Ollama should listen on localhost only. Don’t expose
11434to the internet. - Restrict inbound ports: only 80/443 should be public. On Ubuntu, UFW is fine.
- Fail2ban helps against brute forcing: add it if the gateway is internet-facing and you see repeated 401/403 probes. Use patterns similar to Set Up Fail2ban for Nginx on Ubuntu VPS.
- Set sane timeouts: long generations can tie up workers. Keep Nginx timeouts explicit (
proxy_read_timeout). - Separate internal vs external access: for private admin tools, consider a private tunnel instead of a public endpoint.
If only staff should reach the gateway, a tunnel is often cleaner than maintaining IP allowlists.
See: Set Up Cloudflare Tunnel on a VPS for Private Admin.
Step 7: Optional improvements you can add later
Once the proxy is stable, these upgrades usually deliver the most value:
- Per-key limits: replace the single static token with multiple keys and per-key rate limits (often via an auth service or a small gateway app with Redis).
- Better OpenAI streaming compatibility: implement SSE (
text/event-stream) so OpenAI SDKs can stream tokens naturally. - Structured logging: log request IDs, model name, prompt length, and generation time (but avoid logging sensitive prompts).
- Separate gateway and inference nodes: keep Nginx+gateway on a small VPS, and run Ollama/llama.cpp on a bigger internal server.
Summary: a stable OpenAI-style endpoint on your own server
You now have an OpenAI-compatible HTTPS endpoint that forwards requests to a local model runtime. It’s protected by an API key, basic rate limiting, and logs that make debugging straightforward.
For many internal apps and self-hosted workflows, this is the sweet spot. You get predictable integration without sending prompts off your infrastructure.
If you want a dependable place to run this long-term, start with a HostMyCode VPS for the gateway. Move inference to dedicated servers when you need more CPU, RAM, or GPU headroom.
If you’re shipping internal tools or customer-facing features that expect OpenAI endpoints, HostMyCode gives you predictable infrastructure for self-hosted AI. Run the proxy layer on a HostMyCode VPS, and switch to managed VPS hosting if you want OS patching and baseline hardening handled for you.
FAQ
Can I run this on a small VPS without a GPU?
Yes, as long as you size expectations to the hardware. Use smaller/quantized models, limit concurrency, and expect higher latency. CPU-only works well for low-traffic chat widgets, admin tools, and background tasks.
Is this truly OpenAI compatible?
It’s compatible for the common “chat completions” path: messages in, an assistant message out. If your SDK needs SSE streaming, tool calls, embeddings, or audio endpoints, extend the gateway to match what your client expects.
How do I rotate the API key safely?
Store the token in an environment file (or a secrets manager), reload Nginx, and update apps. If you have multiple callers, move to per-client keys so rotation doesn’t require coordinated downtime.
How do I keep prompts out of logs?
Don’t log request bodies at Nginx, and keep gateway logs minimal. Prefer metadata (request ID, model, timings) over prompt text. If you must debug, enable body logging briefly and only for internal traffic.
What’s the cleanest path to add RAG later?
Keep this gateway as your stable API surface, then add a separate RAG service (Qdrant/pgvector) that your app calls before sending context to the gateway. That split keeps auth and rate limits simpler.