Back to tutorials
Tutorial

vLLM Behind Nginx: OpenAI API on a GPU Server

Deploy vLLM behind Nginx with HTTPS, sane timeouts, and an OpenAI-compatible API on your GPU server.

By Anurag Singh
Updated on Nov 26, 2026
Category: Tutorial
Share article
vLLM Behind Nginx: OpenAI API on a GPU Server

LLM endpoints rarely fail because the model is “wrong.” They fail on the unglamorous parts: TLS, headers, timeouts, and buffering.

This walkthrough shows a production-minded way to run vLLM behind Nginx on a GPU server. You’ll expose an OpenAI-compatible API your apps can call (SDKs, LangChain-style tooling, or your own client).

You’ll run vLLM as a systemd service.

Then you’ll put Nginx in front for HTTPS, tune proxy behavior for long and streaming responses, and add a basic guardrail. The goal is to avoid shipping a public, unauthenticated text generator.

What you’ll build (and what you need)

  • API: vLLM serving an OpenAI-compatible endpoint on 127.0.0.1:8000
  • Edge: Nginx terminates TLS on https://llm.example.com and reverse-proxies to vLLM
  • Auth: simple API key gate at Nginx (good baseline; you can later swap in OAuth2 proxy)
  • Ops: systemd service, logs, health checks, and sane timeouts for streaming/chat

Hardware sizing you can trust

Model size and context length set your floor for VRAM and RAM. If you go too big, vLLM won’t start or will thrash under load.

These are reliable starting points for planning:

  • Minimum “works” GPU box: 1× NVIDIA GPU with 16 GB VRAM, 8 vCPU, 32 GB RAM (small-to-mid instruct model, moderate context)
  • Comfortable for multi-user apps: 1× 24 GB VRAM GPU, 12–16 vCPU, 64 GB RAM (higher concurrency and longer contexts)
  • Disk: 80–150 GB SSD/NVMe (models + cache + logs). Models can consume 10–80+ GB depending on type.

If you’re building an internal endpoint for a team, a HostMyCode dedicated servers plan gives you predictable CPU and storage.

If you’d rather not babysit the base OS and edge stack, consider managed VPS hosting for the reverse proxy and supporting services.

Keep inference on a GPU server where it belongs.

Step 0: Choose a model and understand the trade-offs

vLLM works best with transformer models from the Hugging Face ecosystem. For a first deployment, use a model you already trust in your application.

Keep context length conservative until you’ve watched memory use under real traffic.

  • FP16/BF16 weights: best quality; highest VRAM usage.
  • Quantized weights: lower VRAM and often good enough. Quality can drop, and quantization support varies across stacks.
  • Context length: longer context increases memory pressure. A “bigger context” setting can be the difference between stable and OOM.

One hard constraint: you can’t “Nginx your way out” of an undersized GPU.

If the model plus KV cache don’t fit, the service will crash or refuse to start.

Step 1: Prepare Ubuntu and NVIDIA drivers

This walkthrough assumes Ubuntu Server on a GPU machine. Get the NVIDIA driver working before you touch vLLM.

  1. Update the OS and install basics:
sudo apt update
sudo apt -y upgrade
sudo apt -y install curl git nginx python3-venv python3-pip ufw
  1. Verify NVIDIA is visible:
nvidia-smi

If nvidia-smi fails, stop and fix the driver.

Don’t move on until it shows your GPU and driver info.

  1. Open the firewall only for what you’ll expose (HTTP/HTTPS). Keep vLLM bound to localhost.
sudo ufw allow OpenSSH
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
sudo ufw --force enable
sudo ufw status

If you want an extra layer against drive-by login attempts, pair this with Nginx brute-force protections.

See Set Up Fail2ban for Nginx on Ubuntu VPS.

Step 2: Install vLLM in an isolated environment

For clean operations, create a dedicated Unix user. Then install vLLM in a Python virtual environment.

This keeps upgrades, rollbacks, and permissions straightforward.

sudo useradd -r -m -d /opt/vllm -s /usr/sbin/nologin vllm
sudo mkdir -p /opt/vllm/app /opt/vllm/models
sudo chown -R vllm:vllm /opt/vllm

Create a venv and install vLLM:

sudo -u vllm python3 -m venv /opt/vllm/app/venv
sudo -u vllm /opt/vllm/app/venv/bin/pip install --upgrade pip wheel
sudo -u vllm /opt/vllm/app/venv/bin/pip install vllm

Quick sanity check:

sudo -u vllm /opt/vllm/app/venv/bin/python -c "import vllm; print('vLLM import OK')"

Step 3: Pull the model and decide where it lives

You can let vLLM download a model on first start. That works, but production setups usually prefer explicit paths and predictable permissions.

Create a cache directory for Hugging Face downloads and keep it owned by the vllm user:

sudo mkdir -p /opt/vllm/hf-cache
sudo chown -R vllm:vllm /opt/vllm/hf-cache

If your model requires authentication, you’ll need a Hugging Face token.

Put it in a root-readable-only environment file, not your shell history.

sudo install -m 0600 /dev/null /etc/vllm.env
sudo nano /etc/vllm.env

Example /etc/vllm.env:

HF_HOME=/opt/vllm/hf-cache
HF_TOKEN=your_hf_token_here

This file contains a secret. Keep it readable by root only.

Step 4: Run vLLM as a systemd service (OpenAI-compatible)

Systemd gives you restarts on failure and centralized logs via journalctl.

It also gives you a clear place to define environment variables.

Create a unit file:

sudo nano /etc/systemd/system/vllm.service

Paste this and adjust --model and memory-related flags to your hardware:

[Unit]
Description=vLLM OpenAI-compatible API server
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
User=vllm
Group=vllm
EnvironmentFile=/etc/vllm.env
WorkingDirectory=/opt/vllm
ExecStart=/opt/vllm/app/venv/bin/python -m vllm.entrypoints.openai.api_server \
  --host 127.0.0.1 \
  --port 8000 \
  --model YOUR_MODEL_NAME_OR_PATH \
  --served-model-name local-llm \
  --gpu-memory-utilization 0.90 \
  --max-model-len 4096
Restart=on-failure
RestartSec=2
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=full
ProtectHome=true

[Install]
WantedBy=multi-user.target

Notes you should actually use:

  • --host 127.0.0.1 keeps the API private. Nginx is the only public entry point.
  • --gpu-memory-utilization is your pressure valve. If you hit OOM, lower it (e.g. 0.85).
  • --max-model-len is a stability lever. Reduce it if you need the model to fit reliably.

Enable and start:

sudo systemctl daemon-reload
sudo systemctl enable --now vllm
sudo systemctl status vllm --no-pager

Tail logs if it doesn’t come up:

sudo journalctl -u vllm -n 200 --no-pager

Test locally from the server:

curl -s http://127.0.0.1:8000/v1/models | jq

If jq isn’t installed, either install it (sudo apt -y install jq) or remove the pipe.

Step 5: Put vLLM behind Nginx with TLS, buffering, and timeouts

Nginx handles four things here: TLS termination, access control, proxy behavior for long-running responses, and timeouts that won’t cut off a generation mid-stream.

5.1 Create an Nginx site

Create /etc/nginx/sites-available/llm.example.com:

sudo nano /etc/nginx/sites-available/llm.example.com

Start with an HTTP-only config (TLS comes next).

Replace llm.example.com and set a strong API key value.

map $http_authorization $auth_ok {
  default 0;
  "Bearer REPLACE_WITH_A_LONG_RANDOM_KEY" 1;
}

server {
  listen 80;
  server_name llm.example.com;

  # Let’s Encrypt challenge location will be added by certbot

  location / {
    return 301 https://$host$request_uri;
  }
}

Enable the site and test:

sudo ln -s /etc/nginx/sites-available/llm.example.com /etc/nginx/sites-enabled/llm.example.com
sudo nginx -t
sudo systemctl reload nginx

5.2 Issue a Let’s Encrypt certificate

Install Certbot and request a certificate. This assumes your DNS A/AAAA records already point to the server IP.

sudo apt -y install certbot python3-certbot-nginx
sudo certbot --nginx -d llm.example.com

If you manage DNS for multiple services, keep records explicit and organized. It saves time later.

HostMyCode offers domains and DNS management at https://www.hostmycode.com/domains.

5.3 Add the reverse proxy settings that matter

Edit the TLS server block that Certbot created (same file). Then add the API proxy settings.

The config below works well for OpenAI-style endpoints, including streaming chat completions:

server {
  listen 443 ssl http2;
  server_name llm.example.com;

  ssl_certificate /etc/letsencrypt/live/llm.example.com/fullchain.pem;
  ssl_certificate_key /etc/letsencrypt/live/llm.example.com/privkey.pem;

  # Keep request body sizes predictable. Large prompts can get big.
  client_max_body_size 25m;

  # Basic auth gate via static Bearer token.
  # For anything multi-user, prefer an auth proxy (see note below).
  if ($auth_ok = 0) { return 401; }

  location / {
    proxy_pass http://127.0.0.1:8000;

    # Preserve client info
    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;

    # OpenAI clients can hold connections while generating.
    proxy_connect_timeout 10s;
    proxy_send_timeout 600s;
    proxy_read_timeout 600s;

    # Streaming: avoid buffering responses; reduce latency.
    proxy_buffering off;

    # Some clients benefit from disabling request buffering for streaming uploads.
    # Prompts are usually small enough, but this keeps behavior consistent.
    proxy_request_buffering off;

    # Ensure Nginx doesn't transform chunked responses in unhelpful ways.
    chunked_transfer_encoding on;

    # Basic rate limit placeholder (optional). You can tune properly later.
    # limit_req zone=llm burst=20 nodelay;
  }
}

Reload Nginx:

sudo nginx -t
sudo systemctl reload nginx

If you need a real auth layer (Google/GitHub SSO, groups), put an auth proxy in front of your UI tools and API.

The pattern is covered in Open WebUI With OAuth2 Proxy On A VPS. The same approach applies to an API endpoint.

Step 6: Validate the OpenAI-compatible API through Nginx

From your laptop (or any machine allowed by firewall rules), list models:

curl -s \
  -H "Authorization: Bearer REPLACE_WITH_A_LONG_RANDOM_KEY" \
  https://llm.example.com/v1/models

Then try a chat completion. vLLM follows OpenAI-style routes.

Exact behavior still depends on the model and flags you chose.

curl -s \
  -H "Authorization: Bearer REPLACE_WITH_A_LONG_RANDOM_KEY" \
  -H "Content-Type: application/json" \
  https://llm.example.com/v1/chat/completions \
  -d '{
    "model": "local-llm",
    "messages": [
      {"role": "system", "content": "You are a concise assistant."},
      {"role": "user", "content": "Write a one-sentence status update for a deployment."}
    ],
    "temperature": 0.3
  }' | jq

If you get 401, the Authorization header didn’t match.

If you get 502, Nginx can’t reach vLLM. Common causes are a down service, a wrong port, or binding to the wrong interface.

Step 7: Add the timeouts and limits that prevent “random” production failures

The first real outages usually look like “it just hangs” or “it works locally but not through the proxy.” In practice, it’s almost always a timeout, buffering, or request-size limit.

  • Client request size: set client_max_body_size explicitly. If your app sends large contexts, raise it on purpose.
  • Read timeout: tune proxy_read_timeout to match your longest expected generation time.
  • Buffering: keep proxy_buffering off for streaming endpoints. Buffering adds latency and can break “live token” UX.
  • OS limits: at higher concurrency, raise file descriptor limits and watch Nginx worker connections.

If you run WordPress or other apps on the same host, the symptoms will feel familiar.

The troubleshooting flow is similar to Fix WordPress 504 Gateway Timeout on Nginx VPS, except the upstream is vLLM rather than PHP-FPM.

Step 8: Basic hardening for a self-hosted AI endpoint

LLM endpoints attract abuse because they’re easy to resell. Treat this like you’d treat a billing API: locked down by default, measured access, and careful logs.

Lock it down at the network layer

  • Bind vLLM to localhost: already done via --host 127.0.0.1.
  • Expose only 80/443: UFW rules earlier.
  • Consider private access: if this is internal, don’t publish it. Use a tunnel instead. The pattern in Set Up Cloudflare Tunnel on a VPS for Private Admin also works for LLM endpoints.

Use real authentication

The static bearer token in Nginx is a baseline.

It’s fine for a single app, staging, or controlled internal use.

For multiple clients or human access, use something that can issue identities and enforce policy:

Log responsibly

Prompts can contain secrets. Don’t log request bodies at Nginx.

Stick with default access logs. Avoid enabling request/response “debug” logging in production.

Step 9: Quick diagnostics (the 5 checks you’ll actually use)

  • Is vLLM running?
    sudo systemctl status vllm --no-pager
  • Can the server reach vLLM?
    curl -s http://127.0.0.1:8000/v1/models
  • Is Nginx config valid?
    sudo nginx -t
  • Are you GPU-bound or CPU-bound?
    nvidia-smi (watch memory and utilization) + top or htop
  • Are timeouts killing requests?
    Check Nginx error log: sudo tail -n 200 /var/log/nginx/error.log

Operating notes: upgrades, restarts, and capacity

A few habits make this setup behave like infrastructure instead of a science project:

  • Pin changes: upgrade vLLM in a maintenance window. Restarts drop in-flight requests.
  • Budget for headroom: don’t run --gpu-memory-utilization at 0.99 and expect it to stay up.
  • Plan for spikes: if your apps burst traffic, rate limit at Nginx or at a proxy layer.

Summary: your production-ready vLLM endpoint

You now have vLLM running privately on localhost. Nginx provides HTTPS, proxy settings that work for long generations, and a simple auth gate.

That’s the gap between a demo endpoint and an API your application can rely on.

If you’re serving real traffic and need consistent performance, size hardware for the model and context you actually run.

A GPU-backed server on HostMyCode dedicated servers avoids noisy-neighbor surprises.

managed VPS hosting can offload routine OS and reverse-proxy maintenance.

If you want to self-host AI without making it a second job, keep inference on dedicated hardware and keep the edge stack boring. HostMyCode can help you pick a sensible footprint and keep the host stable over time.

Start with HostMyCode dedicated servers for GPU-grade workloads, or use HostMyCode VPS for the reverse proxy, auth layer, and supporting services around your inference node.

FAQ

Should I expose vLLM directly to the internet?

No. Bind vLLM to 127.0.0.1 and publish only Nginx on 443.

You get TLS, logging, and a single place to enforce access control.

Why disable Nginx proxy buffering for LLM APIs?

Streaming token responses feel “stuck” if Nginx buffers upstream output.

proxy_buffering off pushes tokens to clients as they’re generated.

What’s the most common cause of 502 Bad Gateway here?

vLLM isn’t running, is listening on a different port, or crashed due to GPU memory pressure.

Check systemctl status vllm and journalctl -u vllm first.

How do I prevent runaway costs or abuse?

Put the API behind authentication, add rate limits, and consider an OpenAI-compatible proxy for per-key quotas and auditing.

Keep the endpoint private if it’s only for internal use.

Can I run this on a CPU-only VPS?

You can, but it’s rarely a good experience for interactive apps. Latency rises sharply, and concurrency is limited.

For production use, plan for a GPU server and treat CPU-only as a development fallback.

vLLM Behind Nginx: OpenAI API on a GPU Server | HostMyCode