# vLLM Docker Setup: Serve an LLM in 12 Steps, 75 Min

> Source: <https://shattered.io/vllm-docker-openai-compatible-api-load-test-12-steps-2026/>
> Published: 2026-11-28 10:31:39+00:00

**Recommendation:** Pin the vLLM image tag, keep the container off published ports behind an nginx gateway exposing only /v1/ and /health, and mount a host Hugging Face cache to avoid re-downloading 16 GB of weights on rebuild.
More in the playbook "Inference and self-hosting": <https://wpnews.pro/playbooks/inference-serving>

A single container can turn one GPU box into an OpenAI-style endpoint that your apps, scripts and coding agents all talk to. That container is `vllm/vllm-openai`, and the setup below takes about 75 minutes the first time. The newest vLLM release in the official documentation is [v0.34.0, and the vLLM-Omni quickstart pairs it with PyTorch 2.14.0 and CUDA 13.0](https://docs.vllm.ai/projects/vllm-omni/en/v0.34.0/getting_started/installation/gpu/), so that is the line this vLLM Docker walkthrough targets.

You will finish with a working stack: a pinned vLLM container, a Hugging Face cache that survives restarts, API-key auth, an nginx front door that hides the unauthenticated routes, a streaming Python client, and a load-test script that reports time to first token and tokens per second at five concurrency levels. Every file is copy-paste ready. Every command is one you can rerun after a reboot.

The reason to run vLLM instead of a desktop runtime is concurrency. A tool built for one user at a time is fine for chat, but a team of eight developers hitting the same model exposes the difference quickly. The [comparison of Ollama, LM Studio, llama.cpp and vLLM](https://shattered.io/ollama-vs-lm-studio-vs-llama-cpp-vs-vllm-local-llm-runtimes-2026/) covers which runtime fits which job. This article assumes you already picked vLLM and want it running correctly.

Don't miss new tech stories on Google

Add Shattered once in the Google app and our stories show up in your news suggestions.

[Add now](https://www.google.com/preferences/source?hl=en&q=https%3A%2F%2Fshattered.io%2F)

## Why vLLM in Docker, and What the Finished Stack Looks Like

vLLM started at UC Berkeley’s Sky Computing Lab, and its official documentation now credits more than 2,000 contributors from universities and companies. It is an inference and serving engine, not a model and not a chat app. You point it at a Hugging Face model ID, it loads the weights onto your GPU, carves out the leftover memory for a paged key-value cache, and serves requests with continuous batching. That batching is what lets eight or sixteen simultaneous users share one GPU without each one waiting for the previous answer to finish.

The API surface is the other draw. In the words of the vLLM team’s own documentation, “vLLM provides an HTTP server that implements OpenAI’s Completions API, Chat API, and more!” Current docs also list an Anthropic Messages API and gRPC support. In practice that means any SDK or tool that lets you override a base URL, including the official OpenAI Python client, works against your box after changing two settings.

Docker matters because vLLM’s dependency stack is heavy. A matching PyTorch, CUDA libraries, FlashAttention kernels and the right Python version all have to line up, and a pip install on a workstation that also runs other CUDA projects is a good way to lose an afternoon. The official image ships those pieces pre-matched. Your host only needs a working NVIDIA driver, Docker and the NVIDIA Container Toolkit.

Here is the finished layout. Two containers share a private Docker network. The `vllm` container has no published port, so nothing outside the network can reach it. The `gateway` container runs nginx, listens on 127.0.0.1:8080 on the host, forwards only `/v1/` and `/health`, and returns 404 for everything else. A `.env` file holds the model ID, the pinned image tag and the API key. A Hugging Face cache folder on the host keeps downloaded weights, so a container rebuild never triggers a fresh 16 GB download.

Self-hosting is not automatically cheaper than a hosted API, and the final step shows how to compute your own break-even from measured throughput. For a wider view of when owning the GPU wins, the [self-hosted LLM versus API cost breakdown](https://shattered.io/self-hosted-llm-vs-api-kimi-k3-1-pro-glm-5-3-deepseek-v4-1-mistral-large-4-2026/) works through the same trade-off across several current open-weight families. Also read the [SiliconANGLE piece from November 25, 2026 on whether open-weight models suit your team](https://siliconangle.com/2026/11/25/open-weight-models-are-the-hottest-thing-in-ai-are-they-right-for-you/) if you are still deciding between renting and owning.

## Prerequisites and Versions for a vLLM Docker Setup

You need a Linux host with an NVIDIA GPU. Windows with WSL2 and an NVIDIA GPU works as well, and Docker has reportedly added vLLM support through Docker Model Runner on both WSL2 and Apple silicon, but this tutorial uses plain Docker Compose because it behaves the same everywhere. AMD GPUs use a separate `vllm/vllm-openai-rocm` image and different flags, so they fall outside this walkthrough.

| Component | Version or requirement | Why it matters | 
|---|---|---|
| vLLM image | `vllm/vllm-openai` , pinned to v0.34.0 | The documented release line as of November 2026 | 
| Python (client side) | 3.11 or newer, 3.12 recommended | vLLM’s own requirement, and the OpenAI SDK needs a current interpreter | 
| CUDA | 13.x (13.0 and 13.1 documented as compatible) | The container bundles CUDA, but your driver must be new enough to run it | 
| PyTorch | 2.14.0 in the v0.34.0 quickstart | Already inside the image, no host install | 
| NVIDIA Container Toolkit | 1.20.x line | Lets Docker hand the GPU to the container | 
| Docker | A current Engine with Compose v2 | The `deploy.resources.reservations.devices` syntax needs Compose v2 | 
| GPU memory | 16 GB minimum for an 8B model in bf16 | Weights plus KV cache must fit with headroom | 
| Disk | 40 GB free | Image layers plus model weights | 

Docker Engine 29.10.1 was reportedly the newest Engine build as of November 24, 2026, though that comes from a single release-notes source, so treat it as “any 29.x build” rather than a hard requirement. If you run an older Engine, upgrade before you start. Compose v1 (the standalone `docker-compose` binary) ignores the GPU reservation block and you will chase a confusing “no CUDA device” error later.

You also need a Hugging Face account if your chosen model is gated. Ungated models download without a token. Gated ones need you to accept the license on the model page and paste a read token into `.env`. Budget the first download separately from the setup time, since an 8B model in bf16 is roughly 16 GB and a 26B model is more than three times that.

One honest caveat about hardware. Consumer cards work fine for this tutorial, and the [RTX 5090 local LLM walkthrough](https://shattered.io/run-llm-locally-rtx-5090/) shows what a 32 GB card can hold. Unified-memory boxes behave differently because the CPU and GPU share one pool, which is why the [DGX Spark guide to Ollama and vLLM](https://shattered.io/run-llm-dgx-spark-ollama-vllm-12-steps-2026/) uses a different memory budget. The steps below assume a discrete GPU with its own VRAM.

## Steps 1 to 3: Prepare the Host, the Toolkit and the Project Folder

**Step 1: Verify the GPU, driver and Docker.** Start by confirming the host sees the card and that Docker is current. Run these three commands and keep the output in front of you, because the driver line decides whether the CUDA 13 image will start.

```
nvidia-smi
docker version --format '{{.Server.Version}}'
docker compose version
```

The `nvidia-smi` header prints the driver version and the highest CUDA version that driver supports. Look at the “CUDA Version” field in the top right. If it reads lower than 13.0, update the driver before pulling a CUDA 13 image, or the container will exit at startup with a driver-too-old message. The compose command should report a v2 release. If it prints “command not found”, install the Compose plugin for your distribution.

**Step 2: Install the NVIDIA Container Toolkit and test it.** Docker cannot see your GPU until the toolkit registers the NVIDIA runtime. Follow NVIDIA’s install instructions for your distribution, then configure Docker and restart it:

```
sudo nvidia-ctk runtime configure --runtime=docker
sudo systemctl restart docker
docker run --rm --gpus all ubuntu:24.04 nvidia-smi
```

The last command is the real test. If it prints the same GPU table you saw on the host, the plumbing works. If it errors with “could not select device driver”, the toolkit is missing or Docker was not restarted. Do not move on until this passes, because every later failure would otherwise look like a vLLM bug.

**Step 3: Create the project folder, the .env file and the API key.** Keep everything in one directory so the stack is easy to copy to a second machine.

```
mkdir -p ~/vllm-stack/results
cd ~/vllm-stack
openssl rand -hex 32
```

The `openssl` command prints a 64-character random string. Copy it, because it becomes your API key. Now create `.env` in that folder. Docker Compose reads this file automatically and substitutes the values into `docker-compose.yml` in Step 5:

```
VLLM_TAG=v0.34.0
MODEL_ID=NousResearch/Meta-Llama-3-8B-Instruct
SERVED_NAME=local-chat
MAX_MODEL_LEN=8192
GPU_UTIL=0.90
MAX_SEQS=64
HF_TOKEN=
HF_CACHE=/home/YOURNAME/.cache/huggingface
VLLM_API_KEY=paste-the-openssl-output-here
```

Two choices here deserve a comment. The model ID is the one vLLM’s own docs use in their serving example, picked because it is ungated, small enough for a 24 GB card and well supported. It is an older model, so treat it as the smoke-test default rather than a recommendation for production work. Swap in a current model once the stack runs. And `VLLM_TAG` pins the image. Confirm the exact tag string on Docker Hub, since tags follow the release number, and never use `latest` on a server you care about. Lock the file down with `chmod 600 .env` so other users on the box cannot read the key.

## Step 4: Pick a Model and Do the Memory Math Before You Pull It

vLLM fails in a predictable way when a model does not fit. It prints a CUDA out-of-memory error during startup, or it starts but reports a tiny KV cache that limits you to one or two simultaneous requests. A two-minute calculation avoids both. GPU memory splits into three parts: the model weights, the KV cache that stores attention state for every active token, and a small overhead for activations and CUDA graphs.

Weight memory is parameter count times bytes per parameter. In bf16 or fp16 that is two bytes, so each billion parameters costs about 2 GB. In 8-bit formats it is about 1 GB per billion, and 4-bit quantization gets near 0.5 GB per billion plus some overhead for scales. Mixture-of-experts models trip people up here. A model with 26 billion total parameters still has to keep all 26 billion resident, because the router can pick any expert on any token. Thinking Machines’ Inkling 2 Mini, a 26B-total model under an Apache 2.0 license, is a good example. It decodes like a small model but loads like a medium one.

| Model size (total params) | bf16 weights | 8-bit weights | 4-bit weights (approx.) | Smallest sensible single GPU | 
|---|---|---|---|---|
| 8B | 16 GB | 8 GB | 4 GB | 24 GB card in bf16 | 
| 14B | 28 GB | 14 GB | 7 GB | 24 GB card in 8-bit | 
| 26B (MoE, 3.4B active) | 52 GB | 26 GB | 13 GB | 48 GB card in bf16, 32 GB in 8-bit | 
| 32B | 64 GB | 32 GB | 16 GB | 80 GB card in bf16 | 
| 70B | 140 GB | 70 GB | 35 GB | Two 80 GB cards in bf16 | 

Those figures are straight arithmetic from parameter counts, not benchmarks. They show weights only. The cache comes on top. KV cache per token equals two (keys and values) times the layer count times the number of KV heads times the head dimension times bytes per element. A model with 32 layers, 8 KV heads and a head dimension of 128 in fp16 uses 2 x 32 x 8 x 128 x 2 = 131,072 bytes, or 128 KiB, for every token of context. Read those three numbers from the model’s `config.json` on its Hugging Face page. A single 8,192-token conversation then pins 1 GiB of cache, and sixteen of them pin 16 GiB.

Save this helper as `fit.py` and run it before every model change. It prints how many full-length conversations fit after weights are loaded:

``` python
import argparse

p = argparse.ArgumentParser(description="Will this model fit and how many chats can it hold?")
p.add_argument("--params-b", type=float, required=True, help="total parameters in billions")
p.add_argument("--bytes-per-param", type=float, default=2.0, help="2 for bf16, 1 for 8-bit, 0.5 for 4-bit")
p.add_argument("--layers", type=int, required=True)
p.add_argument("--kv-heads", type=int, required=True)
p.add_argument("--head-dim", type=int, required=True)
p.add_argument("--kv-bytes", type=float, default=2.0, help="2 for fp16 cache, 1 for fp8 cache")
p.add_argument("--ctx", type=int, default=8192, help="tokens per conversation")
p.add_argument("--vram-gb", type=float, required=True)
p.add_argument("--util", type=float, default=0.90, help="gpu-memory-utilization")
p.add_argument("--overhead-gb", type=float, default=2.0)
a = p.parse_args()

weights = a.params_b * a.bytes_per_param
per_token = 2 * a.layers * a.kv_heads * a.head_dim * a.kv_bytes
budget = a.vram_gb * a.util - weights - a.overhead_gb
print(f"weights:            {weights:7.1f} GB")
print(f"KV per token:       {per_token / 1024:7.1f} KiB")
if budget <= 0:
    print("RESULT: does not fit. Use a smaller model, a lower precision or more GPUs.")
    raise SystemExit(1)
tokens = budget * 1e9 / per_token
print(f"KV cache budget:    {budget:7.1f} GB  (about {tokens:,.0f} tokens)")
print(f"full chats at {a.ctx}: {tokens / a.ctx:7.1f} at once")
```

Run it for the default model on a 24 GB card:

```
python3 fit.py --params-b 8 --layers 32 --kv-heads 8 --head-dim 128 --vram-gb 24
```

The output is a five-line summary. For this model on a 24 GB card the weights come to 16.0 GB, the cache budget lands near 3.6 GB (about 27,000 tokens), and that holds roughly three full 8,192-token conversations at once. Three is low for a team, which tells you two things. Either cut `MAX_MODEL_LEN` to 4096 to double the number of slots, or move to an 8-bit build, or use a card with more memory. The [memory math for MoE versus dense open-weight models](https://shattered.io/open-weight-ai-models-moe-vs-dense-280b-vs-27b-memory-math-2026/) goes deeper on why total parameters, not active ones, set your floor.

Before you commit to a model, open its Hugging Face page and check three things. First, the license, because some open-weight releases carry custom terms that limit commercial hosting. Second, whether the repository ships a chat template, since vLLM’s chat endpoint needs one to format messages. Third, whether the model card mentions vLLM. Many recent cards include a ready-made `vllm serve` line with the right flags for that architecture, and copying those flags saves a failed first boot.

## Steps 5 and 6: Write the Compose File and Boot the Server

**Step 5: Create docker-compose.yml.** This file defines both containers. The vLLM service reads every tunable from `.env`, mounts the Hugging Face cache, reserves the GPU and exposes port 8000 only to the internal network. Save it in `~/vllm-stack/`:

```
services:
  vllm:
    image: vllm/vllm-openai:${VLLM_TAG}
    restart: unless-stopped
    ipc: host
    environment:
      - HF_TOKEN=${HF_TOKEN}
      - VLLM_API_KEY=${VLLM_API_KEY}
    volumes:
      - ${HF_CACHE}:/root/.cache/huggingface
    expose:
      - "8000"
    command: >
      --model ${MODEL_ID}
      --served-model-name ${SERVED_NAME}
      --max-model-len ${MAX_MODEL_LEN}
      --gpu-memory-utilization ${GPU_UTIL}
      --max-num-seqs ${MAX_SEQS}
    deploy:
      resources:
        reservations:
          devices:
            - driver: nvidia
              count: all
              capabilities: [gpu]
    healthcheck:
      test: ["CMD", "python3", "-c", "import urllib.request as u; u.urlopen('http://localhost:8000/health', timeout=3)"]
      interval: 15s
      timeout: 5s
      retries: 60
      start_period: 120s

  gateway:
    image: nginx:stable
    restart: unless-stopped
    depends_on:
      vllm:
        condition: service_healthy
    ports:
      - "127.0.0.1:8080:80"
    volumes:
      - ./nginx.conf:/etc/nginx/conf.d/default.conf:ro
```

Each line earns its place. `ipc: host` gives PyTorch the shared memory it needs for tensor parallelism and large batches, and the vLLM Docker docs call it out for exactly that reason. Passing the key as the `VLLM_API_KEY` environment variable instead of a `--api-key` flag keeps it out of `ps` output and out of the container’s command line. `--served-model-name` lets clients ask for `local-chat` instead of a long Hugging Face path, which means you can swap the model later without editing a single client. The long `start_period` and 60 retries matter on first boot, because the weights download and load before the health route answers.

If your tag’s entrypoint turns out to expect the model as a positional argument instead of `--model`, the container will exit with an argument error and the log will say so. In that case move `${MODEL_ID}` to the front of the command without the flag. The release notes for your pinned tag settle which form it wants.

**Step 6: Write the gateway config and start the stack.** Compose will refuse to start the gateway if `nginx.conf` is missing, so create it before the first boot. The file is short, and Step 8 explains each directive:

```
server {
    listen 80;
    server_name _;
    client_max_body_size 4m;

    location = /health {
        proxy_pass http://vllm:8000/health;
        access_log off;
    }

    location /v1/ {
        proxy_pass http://vllm:8000;
        proxy_http_version 1.1;
        proxy_set_header Connection "";
        proxy_set_header Host $host;
        proxy_buffering off;
        proxy_read_timeout 300s;
        proxy_send_timeout 300s;
    }

    location / {
        return 404;
    }
}
```

Now start everything and watch the vLLM log. The first run pulls the image (several GB) and then downloads the model:

```
docker compose up -d
docker compose logs -f vllm
```

Press Ctrl+C to stop following the log without stopping the container. A healthy first boot prints a sequence like the one below. The numbers marked NN depend on your GPU and model, so read the shape rather than the values:

```
INFO  Starting vLLM API server
INFO  Loading model weights took NN.NN GB
INFO  Memory profiling takes NN.NN seconds
INFO  GPU KV cache size: NN,NNN tokens
INFO  Maximum concurrency for 8,192 tokens per request: N.NNx
INFO  Capturing CUDA graphs ...
INFO  Application startup complete.
```

Two lines in that log are worth a screenshot for your runbook. “GPU KV cache size” tells you how many tokens of context the server can hold in total, and “Maximum concurrency” divides that by your `MAX_MODEL_LEN`. If the concurrency figure is below the number of users you expect, go back to Step 4 and shrink the context or the model before you test anything else. The last line, “Application startup complete”, means the server accepts requests. Run `docker compose ps` and confirm both services show as running with the vLLM one marked healthy.

## Step 7: Smoke Test the OpenAI-Compatible API With curl

Before writing any Python, prove the endpoint works with raw HTTP. Load the key into your shell and call the models route. The `set -a` trick exports every variable that `.env` defines:

```
set -a; . ./.env; set +a

curl -s http://127.0.0.1:8080/health -o /dev/null -w "health: %{http_code}\n"

curl -s http://127.0.0.1:8080/v1/models \
  -H "Authorization: Bearer $VLLM_API_KEY"
```

The health check should print `health: 200`. The models call returns a JSON object with `"object":"list"` and a `data` array. Inside it you should see one entry whose `id` equals your `SERVED_NAME`, which is `local-chat` in the sample config. If the id shows a long Hugging Face path instead, the `--served-model-name` flag did not apply, so recheck the compose command block.

Now send a real chat completion. Keep `max_tokens` small for this first call so the response comes back fast:

```
curl -s http://127.0.0.1:8080/v1/chat/completions \
  -H "Authorization: Bearer $VLLM_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "local-chat",
    "messages": [
      {"role": "system", "content": "Answer in one sentence."},
      {"role": "user", "content": "What does continuous batching do?"}
    ],
    "max_tokens": 80,
    "temperature": 0.2
  }'
```

The reply follows the OpenAI schema. Look for `choices[0].message.content` for the answer, `finish_reason` (it reads `stop` for a natural end and `length` if you hit the token cap), and a `usage` block with `prompt_tokens`, `completion_tokens` and `total_tokens`. That usage block becomes your measurement tool later, since the load test counts tokens from it instead of guessing from word counts.

Then test that auth actually bites. Repeat the models call with a wrong key:

```
curl -s -o /dev/null -w "wrong key: %{http_code}\n" \
  http://127.0.0.1:8080/v1/models \
  -H "Authorization: Bearer not-the-key"

curl -s -o /dev/null -w "no key: %{http_code}\n" \
  http://127.0.0.1:8080/v1/models
```

Both calls should print 401. If either prints 200, the container started without a key. The usual cause is an empty or misspelled `VLLM_API_KEY` in `.env`. Compose substitutes an empty string without complaint, and an empty key disables auth. Fix the file, run `docker compose up -d` again so the container recreates with the new environment, and retest.

## Step 8: Lock It Down Behind nginx

The API key is necessary but not sufficient, and the vLLM documentation says so plainly. The relevant line reads: “The –api-key option (or VLLM_API_KEY environment variable) only authenticates requests to endpoints under the /v1, /v2, /inference, and /cohere path prefixes.” Everything else the server exposes stays open to anyone who can reach the port. That includes `/health`, which is harmless, and the metrics and utility routes, which leak model names, queue depth and request counts.

The nginx config from Step 6 handles that with an allow-list. Only two paths pass through. `/health` lets load balancers and Compose probe the server. `/v1/` carries the real API, and vLLM’s own key check still applies to it. Everything else hits `location /` and gets a 404 from nginx, so the request never reaches vLLM at all. Prove it:

```
for path in /metrics /docs /openapi.json /version /v1/models; do
  code=$(curl -s -o /dev/null -w "%{http_code}" http://127.0.0.1:8080$path)
  echo "$path -> $code"
done
```

Without a key, `/v1/models` should print 401 and the other four paths should print 404. Four 404s and one 401 is the target. If `/metrics` returns 200 through port 8080, your nginx config has a stray wildcard location, so compare it with the file above line by line.

Three nginx directives deserve a closer look. `proxy_buffering off` is mandatory for streaming. With buffering on, nginx collects the whole response before forwarding it, and your client sees a long pause followed by every token at once, which looks exactly like a slow server. `proxy_http_version 1.1` with an empty `Connection` header keeps upstream connections alive. `proxy_read_timeout 300s` stops nginx from cutting off a long generation at its 60-second default.

The gateway binds to 127.0.0.1 on purpose. To serve other machines, put TLS in front of it with Caddy or nginx on the host and publish only the TLS port. Never expose plain HTTP with a bearer token over a network you do not control, since the key crosses the wire in clear text. The same reverse-proxy pattern, with per-user keys, appears in the [Ollama API key setup behind a reverse proxy](https://shattered.io/ollama-api-key-reverse-proxy-docker-12-steps-2026/), and the nginx pieces transfer directly to vLLM.

## Step 9: Call the Server From Python With Streaming

Because vLLM speaks the OpenAI wire format, the official OpenAI Python SDK needs no patching. Create a virtual environment on any machine that can reach the gateway, install the SDK and httpx (used in the next step), and export the key:

```
python3 -m venv .venv
. .venv/bin/activate
pip install openai httpx
export VLLM_API_KEY=your-key-here
export SERVED_NAME=local-chat
```

Save the client as `client.py`. It streams tokens as they arrive, measures time to first token, and reads the final usage chunk so it can report an honest tokens-per-second figure:

``` python
import os
import sys
import time

from openai import OpenAI

client = OpenAI(
    base_url=os.environ.get("VLLM_BASE_URL", "http://127.0.0.1:8080/v1"),
    api_key=os.environ["VLLM_API_KEY"],
)
MODEL = os.environ.get("SERVED_NAME", "local-chat")

def ask(prompt, system="You are a concise assistant.", max_tokens=300):
    start = time.perf_counter()
    first = None
    usage = None
    stream = client.chat.completions.create(
        model=MODEL,
        messages=[
            {"role": "system", "content": system},
            {"role": "user", "content": prompt},
        ],
        max_tokens=max_tokens,
        temperature=0.2,
        stream=True,
        stream_options={"include_usage": True},
    )
    for chunk in stream:
        if chunk.choices and chunk.choices[0].delta.content:
            if first is None:
                first = time.perf_counter()
            print(chunk.choices[0].delta.content, end="", flush=True)
        if getattr(chunk, "usage", None):
            usage = chunk.usage
    end = time.perf_counter()
    print()
    if usage and first:
        gen_time = max(end - first, 1e-6)
        print(f"ttft={first - start:.2f}s  tokens={usage.completion_tokens}  "
              f"decode={usage.completion_tokens / gen_time:.1f} tok/s")

if __name__ == "__main__":
    ask(" ".join(sys.argv[1:]) or "Explain paged attention in three sentences.")
```

Run `python client.py "Explain paged attention in three sentences."` and you should see the text appear word by word, followed by a stats line shaped like `ttft=N.NNs tokens=NNN decode=NN.N tok/s`. On a single request the decode rate reflects one stream running alone. Write that number down, because the load test shows how far aggregate throughput climbs when many streams share the GPU.

To point an existing app at the server, change exactly two values: the base URL to your gateway’s `/v1` address and the API key to the one in `.env`. The model name becomes your served name. Libraries that hardcode `api.openai.com` need an environment override such as `OPENAI_BASE_URL`, which the OpenAI SDK reads automatically. The same call shapes the [Ollama API tutorial with curl, Python and streaming](https://shattered.io/ollama-api-tutorial-curl-python-streaming-tools-12-steps/) uses carry over, so code written against one backend usually runs on the other with a base-URL change.

## Step 10: Load Test the Server for Latency and Throughput

A single curl call tells you the server works. It says nothing about how the server behaves when ten people use it at once, and that is the whole reason you picked vLLM. LoadForge’s guide on load testing vLLM starts the same way this step does: “Let’s start with a basic load test against the OpenAI-compatible chat completions endpoint exposed by vLLM.” The [LoadForge guide to load testing vLLM inference servers](https://loadforge.com/guides/ai-llm/load-testing-vllm-inference-servers) covers hosted scenarios if you outgrow the script below.

Three numbers matter. Time to first token (TTFT) is how long a user stares at a blank screen, and it grows when requests queue behind a long prefill. Per-request decode speed is how fast text streams once it starts. Aggregate throughput, the total output tokens per second across all streams, is what you pay for. Continuous batching raises aggregate throughput as concurrency rises, up to a ceiling, while TTFT and per-request speed slowly degrade. The test finds where that trade turns bad for your hardware.

Save this as `loadtest.py`. It sends a fixed set of prompts at several concurrency levels, streams every response, and prints one summary row per level:

``` python
import argparse
import asyncio
import csv
import json
import os
import time

import httpx

PROMPTS = [
    "Explain how a hash map handles collisions.",
    "Write a short checklist for rotating an API key safely.",
    "Summarize the difference between TCP and UDP for a new engineer.",
    "Describe three ways to reduce latency in a web service.",
    "Explain what a database index does and when it hurts.",
    "Give a plain-English definition of idempotency with an example.",
]

def pct(values, q):
    if not values:
        return float("nan")
    ordered = sorted(values)
    idx = min(len(ordered) - 1, max(0, round(q / 100 * (len(ordered) - 1))))
    return ordered[idx]

async def one(client, url, headers, model, prompt, max_tokens):
    body = {
        "model": model,
        "messages": [{"role": "user", "content": prompt}],
        "max_tokens": max_tokens,
        "temperature": 0.0,
        "stream": True,
        "stream_options": {"include_usage": True},
    }
    t0 = time.perf_counter()
    first = None
    tokens = 0
    async with client.stream("POST", url, headers=headers, json=body, timeout=300) as r:
        if r.status_code != 200:
            await r.aread()
            return {"ok": False, "status": r.status_code}
        async for line in r.aiter_lines():
            if not line.startswith("data: "):
                continue
            data = line[6:]
            if data == "[DONE]":
                break
            obj = json.loads(data)
            choices = obj.get("choices") or []
            if choices and choices[0].get("delta", {}).get("content") and first is None:
                first = time.perf_counter()
            if obj.get("usage"):
                tokens = obj["usage"]["completion_tokens"]
    t1 = time.perf_counter()
    return {"ok": True, "ttft": (first or t1) - t0, "total": t1 - t0, "tokens": tokens}

async def run_level(base, key, model, conc, n, max_tokens):
    url = base.rstrip("/") + "/chat/completions"
    headers = {"Authorization": f"Bearer {key}"}
    sem = asyncio.Semaphore(conc)
    limits = httpx.Limits(max_connections=conc + 4)
    async with httpx.AsyncClient(limits=limits) as client:

        async def guarded(i):
            async with sem:
                return await one(client, url, headers, model, PROMPTS[i % len(PROMPTS)], max_tokens)

        t0 = time.perf_counter()
        results = await asyncio.gather(*(guarded(i) for i in range(n)))
        wall = time.perf_counter() - t0
    ok = [r for r in results if r["ok"]]
    toks = sum(r["tokens"] for r in ok)
    return {
        "conc": conc,
        "ok": f"{len(ok)}/{n}",
        "ttft_p50_ms": round(pct([r["ttft"] for r in ok], 50) * 1000),
        "ttft_p95_ms": round(pct([r["ttft"] for r in ok], 95) * 1000),
        "req_p95_s": round(pct([r["total"] for r in ok], 95), 2),
        "agg_tok_s": round(toks / wall, 1),
        "per_req_tok_s": round(toks / max(sum(r["total"] for r in ok), 1e-6), 1),
    }

async def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--base", default=os.environ.get("VLLM_BASE_URL", "http://127.0.0.1:8080/v1"))
    ap.add_argument("--model", default=os.environ.get("SERVED_NAME", "local-chat"))
    ap.add_argument("--levels", default="1,4,8,16,32")
    ap.add_argument("--requests", type=int, default=48)
    ap.add_argument("--max-tokens", type=int, default=200)
    ap.add_argument("--out", default="results/load.csv")
    a = ap.parse_args()
    key = os.environ["VLLM_API_KEY"]

    await run_level(a.base, key, a.model, 1, 2, 16)  # warm-up, not recorded
    rows = []
    for level in [int(x) for x in a.levels.split(",")]:
        row = await run_level(a.base, key, a.model, level, max(a.requests, level * 2), a.max_tokens)
        rows.append(row)
        print(row)
    os.makedirs(os.path.dirname(a.out), exist_ok=True)
    with open(a.out, "w", newline="") as f:
        w = csv.DictWriter(f, fieldnames=list(rows[0].keys()))
        w.writeheader()
        w.writerows(rows)
    print("saved", a.out)

asyncio.run(main())
```

Run it with `python loadtest.py`. The warm-up request matters, because the first call after boot pays for lazy initialization and would skew the concurrency-1 row. Expect each level to take a minute or two. The summary lines have this shape, with NNN standing in for your measured values:

```
{'conc': 1,  'ok': '48/48', 'ttft_p50_ms': NNN, 'ttft_p95_ms': NNN, 'req_p95_s': N.NN, 'agg_tok_s': NN.N,  'per_req_tok_s': NN.N}
{'conc': 4,  'ok': '48/48', 'ttft_p50_ms': NNN, 'ttft_p95_ms': NNN, 'req_p95_s': N.NN, 'agg_tok_s': NNN.N, 'per_req_tok_s': NN.N}
{'conc': 8,  'ok': '48/48', ...}
{'conc': 16, 'ok': '48/48', ...}
{'conc': 32, 'ok': '48/48', ...}
saved results/load.csv
```

Read the table from top to bottom. `agg_tok_s` should rise sharply from concurrency 1 to 8, then flatten as the GPU saturates. `per_req_tok_s` should fall as more streams compete. The right operating point is usually the level just before aggregate throughput stops climbing and p95 TTFT crosses whatever delay your users tolerate. Any `ok` value below the request count means errors, and the troubleshooting section below maps each status code to a fix. A count like 47/48 at concurrency 32 usually means the server hit `MAX_SEQS` and some requests timed out waiting in the queue.

## Step 11: Tune the Server Against Your Own Load Test

Tuning without a baseline is guesswork, so keep `results/load.csv` from Step 10 and change one flag at a time. Edit `.env` or the compose command, run `docker compose up -d` to recreate the container, wait for the health check, then rerun `python loadtest.py --out results/load-v2.csv`. Compare the two files. A change that does not move the numbers was not worth making.

| Flag | What it controls | Raise or lower it when | Risk | 
|---|---|---|---|
| `--max-model-len` | Longest prompt plus reply a single request may use | Lower it if the startup log shows a small concurrency figure and your users never send long prompts | Requests above the cap fail with a length error | 
| `--gpu-memory-utilization` | Fraction of VRAM vLLM may claim | Raise it a little above the 0.90 starting point on a dedicated GPU for a bigger cache | Out-of-memory crashes if anything else touches the card | 
| `--max-num-seqs` | Most requests decoded at the same moment | Raise for many short chats, lower to protect latency | Higher values add queueing delay for each user | 
| `--tensor-parallel-size` | Splits one model across several GPUs | Set it to the GPU count when weights exceed one card | Needs fast links between cards and adds sync cost | 
| `--kv-cache-dtype` | Precision of the stored attention state | Try fp8 to roughly double the number of cached tokens | Small quality drift on some models, so recheck outputs | 
| `--quantization` | Loads pre-quantized weights | Use it when a model only fits in 8-bit or 4-bit form | Quality and speed vary by format and kernel support | 
| `--enable-prefix-caching` | Reuses cached state for repeated prompt prefixes | Keep it on when every request begins with the same long system prompt | Little gain on fully unique prompts | 

Start with `--max-model-len`, because it has the biggest effect for the least risk. Most chat workloads use a few thousand tokens per request, yet the default is the model’s full advertised context. That default can be huge. A model that advertises a 1M-token window will reserve cache space as if each request might use all of it, and the server may refuse to start or report room for a single concurrent request. Setting 8192 or 16384 turns that same GPU into a server that handles many users.

Next, adjust `--max-num-seqs` using the load-test table. If aggregate throughput was still climbing at concurrency 32 and p95 TTFT looked fine, raise it. If TTFT exploded at 16, lower it, and accept that extra requests wait in a queue instead of slowing everyone. Queueing is usually the kinder failure mode, since each user sees a short wait and then a fast stream. Overloading the batch makes every stream slow.

Prefix caching deserves a specific experiment if your app sends a long, fixed system prompt. Run the load test with every prompt prefixed by the same 1,500-token block, once with the feature on and once off, and compare TTFT. Recent vLLM releases may already enable it by default for supported setups, so check the startup log before assuming you need the flag. Keep the final winning settings in `.env` with a comment line recording the date and the load-test file that justified them.

## Step 12: Monitor, Pin Versions and Price Your Box

The last step turns a working demo into something you can leave running. Three habits cover most of it. Pin the image tag and change it deliberately. Watch the server’s own metrics. Know what a million tokens costs you, so you can tell whether the GPU is earning its keep.

**Pinning.** Your `.env` already carries `VLLM_TAG=v0.34.0`. Upgrades should follow a fixed routine: read the release notes, change the tag on a spare port or a second machine, rerun `loadtest.py`, compare against the old CSV, then switch. The vLLM site announced v0.34.0 with ten new models, and releases move fast enough that a surprise upgrade can change default behavior under you.

**Metrics.** vLLM serves Prometheus-format metrics on `/metrics`. Because the gateway hides that route from outside, scrape it from inside the Docker network. Add a Prometheus container to the same compose project with a target of `vllm:8000`, or fetch the metrics ad hoc from inside the container:

``` python
docker compose exec vllm python3 -c "import urllib.request as u; print(u.urlopen('http://localhost:8000/metrics').read().decode()[:2000])"
```

Watch the number of running and waiting requests and the KV cache usage. A waiting count that stays above zero means you are over capacity.

**Cost.** Save this as `cost.py`. It converts your measured throughput and a GPU price into a cost per million output tokens, then compares that against a hosted price:

``` python
import argparse

p = argparse.ArgumentParser(description="Self-hosted vs hosted cost per million output tokens")
p.add_argument("--gpu-hour", type=float, required=True, help="cost of the GPU per hour in USD")
p.add_argument("--agg-tok-s", type=float, required=True, help="aggregate output tokens/s from loadtest.csv")
p.add_argument("--busy", type=float, default=0.25, help="fraction of the day the GPU is actually busy")
p.add_argument("--hosted-out", type=float, required=True, help="hosted price per million output tokens")
a = p.parse_args()

tokens_per_hour_full = a.agg_tok_s * 3600
full_load = a.gpu_hour / tokens_per_hour_full * 1e6
at_busy = full_load / a.busy
print(f"self-hosted at 100% busy: ${full_load:6.2f} per 1M output tokens")
print(f"self-hosted at {a.busy:.0%} busy: ${at_busy:6.2f} per 1M output tokens")
print(f"hosted API:               ${a.hosted_out:6.2f} per 1M output tokens")
verdict = "self-hosting wins" if at_busy < a.hosted_out else "the hosted API wins"
print(f"at this utilization, {verdict}")
if at_busy >= a.hosted_out:
    needed = full_load / a.hosted_out
    print(f"break-even needs the GPU busy at least {needed:.0%} of the time")
```

Here is the arithmetic with hypothetical inputs. Hugging Face’s Jobs pricing page lists a single NVIDIA H200 at $5 an hour. If your load test showed 1,000 aggregate output tokens per second, one hour of full load produces 3.6 million tokens, so you divide the hourly GPU cost by that token count to get the cost per million output tokens. At a realistic 25 percent busy rate the same box produces far fewer tokens per hour while the hourly bill stays the same, so the cost per million tokens rises several times over. Those inputs are examples, so replace them with your own CSV values and your own GPU cost, whether that is a cloud rate or your card’s amortized price plus electricity.

| Reference point (per 1M tokens) | Input | Output | Source | 
|---|---|---|---|
| OpenAI GPT-6.2 Astra (hosted) | $8 | $40 | OpenAI model docs, November 25, 2026 | 
| OpenAI GPT-6.2 Sol (hosted) | $2 | $10 | OpenAI model docs, November 2026 | 
| Average closed model via Hugging Face providers | $1.27 | $6.36 | Hugging Face and OpenRouter announcement, November 16, 2026 | 
| Average open-weight model via Hugging Face providers | $0.28 | $1.62 | Same announcement | 
| Your vLLM box | n/a | Output of `cost.py` | Your load test and GPU price | 

The hosted rows come from [OpenAI’s model comparison page](https://developers.openai.com/api/docs/models/compare), and the H200 hourly figure comes from [Hugging Face’s Jobs pricing page](https://huggingface.co/docs/hub/main/en/jobs-pricing). Notice the gap between the average open-weight price at hosted providers and the closed-model average. If your workload fits an open model, a pay-per-token provider can undercut your own idle GPU, which is the same conclusion the [Ollama Cloud pricing versus self-hosted vLLM comparison](https://shattered.io/ollama-cloud-pricing-vs-self-hosted-vllm-20-pro-plan-2026/) reaches for light workloads. Self-hosting wins on privacy, on steady heavy traffic, and on control over versions and models.

Your finished project folder should now look like this:

```
vllm-stack/
  .env                  # tag, model, key (chmod 600)
  docker-compose.yml    # vllm + nginx gateway
  nginx.conf            # allow-list: /health and /v1/ only
  fit.py                # memory math before any model change
  client.py             # streaming client with TTFT and tok/s
  loadtest.py           # concurrency sweep, writes CSV
  cost.py               # break-even calculator
  results/              # load.csv from each tuning run
```

Add `docker compose logs --tail 200 vllm` to your habits and set Docker’s log driver to rotate (`max-size` and `max-file` options in the daemon config), since an inference server logs every request and can fill a small disk in weeks. The `restart: unless-stopped` policy already brings the stack back after a reboot, provided the Docker service itself starts at boot.

## Seven Common Pitfalls That Waste an Evening

**1. Running the latest tag.** It feels convenient until a restart pulls a new release with different defaults and your tuned settings stop making sense. Pin to a version tag and upgrade on purpose.

**2. An empty API key.** Docker Compose substitutes a blank string without warning if the variable is missing, and vLLM then runs with auth off. Always run the 401 test from Step 7 after any change to `.env`.

**3. Publishing port 8000 directly.** The key only covers the `/v1`, `/v2`, `/inference` and `/cohere` prefixes. A published port exposes everything else. Keep vLLM on the internal network and let the gateway decide what outsiders can see.

**4. Leaving max-model-len at the model default.** Long-context models reserve cache for contexts your users never reach. Cap it to what the app needs, as Step 11 describes.

**5. Setting gpu-memory-utilization too high.** On a card that also drives a monitor, or that shares a host with another CUDA job, a very high setting leaves little memory for anything else and can cause out-of-memory crashes under load rather than at boot. Leave some headroom unless the GPU is dedicated.

**6. Comparing load tests that are not comparable.** If one run uses 200 output tokens and another uses 500, or the prompts differ, the tokens-per-second figures mean different things. Fix the prompts, the `max_tokens` value and the request count, and change only the server setting under test.

**7. Trusting the first request.** The first call after boot includes lazy initialization. Warm up, as `loadtest.py` does, before you record anything. For more hands-on builds in this area, browse the site’s [AI and machine learning coverage](https://shattered.io/category/ai-machine-learning/).

## Troubleshooting: 12 Errors and Their Fixes

### Startup failures

- **“could not select device driver nvidia” from Docker.** The NVIDIA Container Toolkit is not registered. Rerun the`nvidia-ctk runtime configure` command from Step 2, restart Docker, and retest with the plain`ubuntu` container.
- **CUDA out of memory during startup.** The weights plus cache did not fit. Run`fit.py` , then lower`MAX_MODEL_LEN` , lower`GPU_UTIL` a notch if another process holds memory, or switch to an 8-bit build. Check`nvidia-smi` for stray processes holding VRAM.
- **“The model’s max seq len is larger than the maximum number of tokens that can be stored in KV cache.”** The server tells you exactly what happened. Reduce`MAX_MODEL_LEN` to the value it suggests or free more memory.
- **A driver or CUDA version error at launch.** Your host driver is older than the image’s CUDA build expects. Update the driver, or pin an image tag built for an older CUDA release.
- **“unrecognized arguments” and the container exits.** Your tag’s entrypoint handles the model differently. Check the logs, then follow the release notes for the exact form, typically moving the model to a positional argument.
- **A 401 or 403 from Hugging Face while downloading.** The model is gated. Accept the license on the model page, create a read token, put it in`HF_TOKEN` , and recreate the container.
- **Bus error or shared memory errors.** The container lacks shared memory. Keep`ipc: host` in the compose file, or set a large`shm_size` instead.

### Auth and routing failures

- **401 Unauthorized from a correct-looking key.** Look for whitespace or a trailing newline in the key. Print it with`echo "[$VLLM_API_KEY]"` and check the brackets hug the text. Also confirm the header is`Authorization: Bearer KEY` .
- **404 “model does not exist”.** The client’s model name must match`SERVED_NAME` exactly. Call`/v1/models` and copy the id it returns.
- **502 Bad Gateway from nginx right after boot.** The gateway started before vLLM finished loading. The`depends_on` health condition prevents this, so confirm the healthcheck block exists and that you are on Compose v2.

### Performance and streaming problems

- **The reply arrives all at once instead of streaming.** nginx is buffering. Confirm`proxy_buffering off` in the`/v1/` block and that no outer proxy or CDN also buffers.
- **The model downloads again after every rebuild.** The cache volume is not mapped where Hugging Face looks. Use an absolute path for`HF_CACHE` , make sure the folder is writable, and keep the mount target as`/root/.cache/huggingface` .

When none of these match, read the first error line in `docker compose logs vllm` from the top of the startup sequence, not the last line. The final line is often just a consequence, and the root cause scrolled past a few hundred lines earlier.

## Advanced Tips for Production Use

**Split large models across GPUs.** When weights exceed one card, add `--tensor-parallel-size 2` (or your GPU count) and keep `ipc: host`. Match the cards, because the slowest one sets the pace. Fast interconnects such as NVLink help, while PCIe-only pairs lose some throughput to synchronization.

**Add per-client rate limits.** A shared key invites one noisy script to starve everyone. Put a request limit in nginx, keyed on the client address or on the key header. This snippet sits above the `server` block and inside the `/v1/` location:

```
# above the server block
limit_req_zone $http_authorization zone=perkey:10m rate=5r/s;

# inside location /v1/
limit_req zone=perkey burst=20 nodelay;
limit_req_status 429;
```

**Turn on tool calling.** Agent frameworks send function schemas to the chat endpoint. vLLM supports that when you start it with `--enable-auto-tool-choice` and a `--tool-call-parser` that matches your model family. Check the model card for the right parser name. The [Python agent build with open-weight tool calling](https://shattered.io/build-ai-agent-python-open-weight-tool-calling-12-steps-2026/) shows a loop that works against exactly this kind of endpoint.

**Run a blue-green upgrade.** Copy the project to a second folder, change the compose project name, publish the gateway on a different port, load the new tag there, and run the same load test. Switch your clients over once the new CSV matches or beats the old one. Rolling back is then a one-line URL change.

**Quantize before you buy hardware.** An 8-bit or 4-bit build of a larger model often beats a full-precision smaller model on quality per dollar, and it fits the same card. Rerun `fit.py` with `--bytes-per-param 1` or `0.5`, then run a quality spot check on your own prompts, not a generic benchmark.

## Frequently Asked Questions

### Is vLLM free to run in Docker?

The software is open source and free. You pay for the GPU, whether that is hardware you own, a rented cloud instance, or electricity. Model weights are free to download for open-weight releases, but each model has its own license, so check the terms on its Hugging Face page before using it commercially.

### What is the difference between vLLM and Ollama?

Ollama optimizes for easy local use and model management on one machine. vLLM optimizes for serving many concurrent requests on a GPU with continuous batching and a paged KV cache. If one person chats with a model, Ollama is simpler. If a team or an application shares one model, vLLM usually delivers more aggregate throughput from the same card.

### How much GPU memory do I need?

Weights need about 2 GB per billion parameters in bf16, 1 GB in 8-bit and roughly 0.5 GB in 4-bit. Add the KV cache for your context length and number of simultaneous users, plus a couple of gigabytes of overhead. A 24 GB card runs an 8B model in bf16 for a handful of concurrent chats. Use `fit.py` for your exact model.

### Can I use the OpenAI Python SDK with vLLM?

Yes. Set `base_url` to your server’s `/v1` address, pass your key as `api_key`, and use your served model name. Chat completions, streaming and usage reporting all follow the OpenAI format. Support for newer hosted-only features, such as every Responses API option, can differ, so test the specific calls your app uses.

### Is the –api-key flag enough to expose the server to the internet?

No. The key covers only the documented route prefixes and sends no encryption. Put a reverse proxy with TLS in front, allow only the routes you need, add rate limits, and keep the vLLM container off the public network. Treat the key as one layer in a stack, never as the whole defense.

### How do I update vLLM safely?

Read the release notes, then run the new tag next to the old one on a different port. Run `loadtest.py` against both and compare the CSV files. Switch clients only when the new version matches the old on latency and error counts. Keep the previous tag in `.env` comments so you can roll back in a minute.

### How many users can one GPU serve?

It depends on the model, the context length and how fast users expect replies, so measure instead of guessing. Run the load test at 1, 4, 8, 16 and 32 concurrent streams, then pick the highest level where p95 time to first token still feels acceptable. Chat users tolerate a short pause before the first word far better than a slow stream after it.
