Serve a Llama Model with vLLM and Docker: Full Guide

Running Meta’s Llama behind your own API endpoint used to mean wiring together a sampler, a tokenizer, and a web server by hand. vLLM compresses all of that into one process: a high-throughput inference engine with an OpenAI-compatible HTTP server built in. Put it in Docker and the whole deployment becomes a single reproducible container.

This guide covers the full path on a Linux host with an NVIDIA GPU: installing the container toolkit, pulling the official vLLM image, serving Llama 3.1 8B Instruct, verifying the endpoint, tuning it, and hardening it for real traffic. Most of the wall-clock time is downloads; the hands-on part takes about half an hour.

Why vLLM Instead of a Plain Inference Loop

Three things make vLLM worth the setup:

  • PagedAttention manages the KV cache in fixed-size blocks instead of one contiguous slab per request, so memory fragmentation stays low and more requests fit on the card.
  • Continuous batching lets new requests join the batch mid-generation instead of waiting for the whole batch to finish. Under concurrent load this keeps the GPU busy in a way naive batching does not.
  • An OpenAI-compatible API means existing client code works by changing the base URL. /v1/chat/completions, /v1/completions, and /v1/models all behave the way OpenAI SDK users expect.

One honest caveat before you invest the effort: if exactly one person will query the model at a time on a laptop GPU, this machinery buys you little. A simpler tool like Ollama gets you running faster. vLLM earns its keep when requests arrive concurrently and GPU utilization actually matters.

Prerequisites

  • An NVIDIA GPU with working drivers. Run nvidia-smi; if it prints a table, you are good.
  • Docker Engine on Linux, version 19.03 or newer.
  • A Hugging Face account with the Llama license accepted. Llama weights are gated: open the model page for meta-llama/Meta-Llama-3.1-8B-Instruct, accept the license terms, and create a read token. Without this step every download attempt fails with a 401.
  • Free disk space in the tens of gigabytes. The 8B weights are roughly 16 GB and the vLLM image itself is several more.

Step 1: Install the NVIDIA Container Toolkit

Stock Docker cannot see your GPU until you install NVIDIA’s container toolkit:

distribution=$(. /etc/os-release;echo $ID$VERSION_ID)
curl -fsSL https://nvidia.github.io/libnvidia-container/gpgkey 
  | sudo gpg --dearmor -o /usr/share/keyrings/nvidia-container-toolkit-keyring.gpg
curl -s -L https://nvidia.github.io/libnvidia-container/$distribution/libnvidia-container.list 
  | sed 's#deb https://#deb [signed-by=/usr/share/keyrings/nvidia-container-toolkit-keyring.gpg] https://#g' 
  | sudo tee /etc/apt/sources.list.d/nvidia-container-toolkit.list
sudo apt-get update && sudo apt-get install -y nvidia-container-toolkit
sudo nvidia-ctk runtime configure --runtime=docker
sudo systemctl restart docker

Verify the GPU is visible inside a container:

docker run --rm --gpus all nvidia/cuda:12.4.0-base-ubuntu22.04 nvidia-smi

If that prints your GPU table, the plumbing works.

Step 2: Pick a Model and Do the VRAM Math

The official image is vllm/vllm-openai, which bundles the OpenAI-compatible server. Before pulling it, decide which weights fit your card. The back-of-the-envelope math: multiply parameter count by bytes per parameter (2 for FP16/BF16, 1 for FP8/INT8, 0.5 for 4-bit), then add roughly 30 to 50 percent headroom for the KV cache, activations, and framework overhead.

Model FP16 weights (approx.) Realistic minimum for serving
Llama 3.2 3B Instruct ~6 GB 12 GB card, short context
Llama 3.1 8B Instruct ~16 GB 24 GB card (e.g., RTX 4090)
Llama 3.3 70B Instruct ~140 GB 2x 80 GB GPUs, or 4-bit quant on smaller cards

These are estimates, not guarantees; long context windows and high concurrency both push the real number up. If the full-precision weights do not fit, quantization is the usual answer: a 4-bit AWQ build of the 8B model needs roughly 4 to 5 GB for weights, and vLLM loads it with --quantization awq. FP8 (--quantization fp8) is another option but needs a recent data-center GPU such as Hopper or newer. Either way, download quantized checkpoints only from publishers you trust, since modified weights can behave differently from the originals.

This guide uses meta-llama/Meta-Llama-3.1-8B-Instruct, the instruction-tuned 8B model, as the running example.

Step 3: Pull the Image and Run the Container

Generate an API key first so the endpoint is never open to the world without auth:

export HF_TOKEN="hf_your_token_here"
export VLLM_API_KEY="$(openssl rand -hex 16)"
echo "$VLLM_API_KEY"

Save that key somewhere; you will need it for every request. Then start the server:

docker run -d 
  --name vllm-llama 
  --gpus all 
  --ipc=host 
  -p 8000:8000 
  -e HUGGING_FACE_HUB_TOKEN="$HF_TOKEN" 
  -v hf-cache:/root/.cache/huggingface 
  vllm/vllm-openai:latest 
  --model meta-llama/Meta-Llama-3.1-8B-Instruct 
  --served-model-name llama-3.1-8b 
  --max-model-len 8192 
  --api-key "$VLLM_API_KEY"

What each part does:

  • --gpus all hands every GPU to the container. Use --gpus '"device=0"' to pin one card on a multi-GPU box.
  • --ipc=host gives the container access to the host’s shared memory, which the NCCL communication backend wants. Skipping it is a classic source of cryptic startup hangs.
  • -v hf-cache:/root/.cache/huggingface stores downloaded weights in a named volume, so restarting the container does not re-download 16 GB.
  • The image entrypoint is vllm serve, so everything after the image name is a server flag.
  • --served-model-name sets the friendly name clients use in API calls, instead of the full Hugging Face repo id.
  • --max-model-len 8192 caps the context window. vLLM reserves KV cache up front based on this number, so it directly controls memory use.

Watch the startup logs. The first boot downloads the weights and takes several minutes:

docker logs -f vllm-llama

You are ready when the logs show the Uvicorn server listening on port 8000. If instead you see 401 errors mentioning the Hugging Face hub, the license was not accepted or the token lacks access to the gated repo. Fix that on the Hugging Face website, not in Docker.

Step 4: Verify the Server

Check the model list:

curl http://localhost:8000/v1/models 
  -H "Authorization: Bearer $VLLM_API_KEY"

Then send a real chat request:

curl http://localhost:8000/v1/chat/completions 
  -H "Content-Type: application/json" 
  -H "Authorization: Bearer $VLLM_API_KEY" 
  -d '{
    "model": "llama-3.1-8b",
    "messages": [{"role": "user", "content": "Explain PagedAttention in two sentences."}],
    "max_tokens": 120
  }'

Note that the model field must match --served-model-name, not the Hugging Face repo id. Expect the first request to be slow: model loading plus CUDA graph capture happens once, and only then does token generation reach full speed. Send one warmup request before you judge latency or add the endpoint to a load balancer.

Step 5: Make It Repeatable with Docker Compose

A compose file turns the long docker run into version-controlled config. Create a .env file with your secrets:

HF_TOKEN=hf_your_token_here
VLLM_API_KEY=your_generated_key_here

Then docker-compose.yml:

services:
  vllm:
    image: vllm/vllm-openai:latest
    container_name: vllm-llama
    ipc: host
    ports:
      - "8000:8000"
    environment:
      - HUGGING_FACE_HUB_TOKEN=${HF_TOKEN}
    volumes:
      - hf-cache:/root/.cache/huggingface
    command:
      - --model
      - meta-llama/Meta-Llama-3.1-8B-Instruct
      - --served-model-name
      - llama-3.1-8b
      - --max-model-len
      - "8192"
      - --gpu-memory-utilization
      - "0.9"
      - --api-key
      - ${VLLM_API_KEY}
    deploy:
      resources:
        reservations:
          devices:
            - driver: nvidia
              count: 1
              capabilities: [gpu]
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:8000/health"]
      interval: 30s
      timeout: 10s
      retries: 3
      start_period: 240s
    restart: unless-stopped

volumes:
  hf-cache:

Start it with docker compose up -d. The start_period of four minutes keeps Docker from killing the container while the model loads, which is the most common reason a compose-based vLLM setup flap-loops on first boot.

Tuning Knobs Worth Knowing

Flag What it does When to touch it
--max-model-len Caps context length; KV cache is reserved up front from this Lower it first when you hit out-of-memory errors
--gpu-memory-utilization Fraction of GPU memory vLLM may claim (default 0.9) Drop to 0.8-0.85 if the container dies during startup memory profiling
--max-num-seqs Max concurrent sequences Lower it if memory pressure appears only under load
--tensor-parallel-size Shards the model across N GPUs on one machine Set to 2 or 4 for 70B models on multi-GPU hosts
--enable-prefix-caching Reuses KV cache for repeated prompt prefixes Turn on when many requests share a system prompt
--enforce-eager Disables CUDA graphs Debugging aid for strange crashes; costs throughput, so do not leave it on
--dtype Weight/activation precision Usually leave on auto; bfloat16 is a common explicit choice on Ampere and newer

The single most useful rule: out-of-memory at startup is almost always the context window. Halving --max-model-len is a bigger lever than any other flag, because the KV cache reservation scales with it.

Common Failure Modes

  • 401 from the Hugging Face hub. License not accepted, or the token belongs to an account that has not accepted it. Accept the license on the model page and generate a fresh token.
  • CUDA out of memory during startup. Reduce --max-model-len, lower --gpu-memory-utilization, or move to a quantized checkpoint.
  • Bind error on port 8000. Something already listens there. Either stop it or map a different host port with -p 8001:8000.
  • First tokens are slow, then it speeds up. Normal. CUDA graph capture and kernel autotuning happen once per boot.
  • Requests hang with --ipc=host missing. Add it. The failure mode is a silent stall during NCCL init, which is miserable to debug without knowing to look for it.

Hardening for Production

A working container is not a production deployment. Minimum viable hardening:

  1. Keep the API key. Never publish port 8000 without --api-key, and rotate the key if it ever appears in a log, a screenshot, or a chat message.
  2. Terminate TLS in front of it. vLLM speaks plain HTTP. Put Caddy or nginx in front; with Caddy the whole config can be two lines: your domain, then reverse_proxy localhost:8000.
  3. Pin the image tag. latest moves under you without warning. Pin a release tag you have tested, and upgrade deliberately.
  4. Monitor queue depth and cache pressure. vLLM exports Prometheus metrics including running request count (vllm:num_requests_running) and KV cache usage (vllm:gpu_cache_usage_perc). Sustained queue growth means you need more replicas or a smaller model, not more flags.
  5. Back up the weights volume. Re-downloading 16 GB after a host rebuild is downtime you can avoid with a volume backup.

When vLLM Is the Wrong Tool

No NVIDIA GPU on the box? vLLM’s Docker path assumes CUDA. For CPU inference or small cards, llama.cpp or Ollama are the pragmatic choice. Prototyping a single-user app and dreading ops work? A managed inference API removes the GPU, the drivers, and the 3 a.m. pages in exchange for per-token pricing. vLLM is the right call when you have the hardware, expect concurrent traffic, and want an OpenAI-compatible endpoint you fully control.

Deployment Checklist

Pull vllm/vllm-openai, accept the Llama license and set your Hugging Face token, size the model against your VRAM with the 30 to 50 percent headroom rule, run the container with --ipc=host and a persistent weights volume, verify with /v1/models and one warmup chat request, then move the flags into Docker Compose. Before you share the URL: pin the image tag, set the API key, and put a TLS reverse proxy in front. Which weights deserve that VRAM is its own question; our roundup of the best open-source LLMs for self-hosting compares the current Llama, Qwen, Mistral, and DeepSeek options.

Ditulis oleh

Firdaus Safari Putra

Founder, PT FirKaizen Digital Solutions

Firdaus Safari Putra adalah founder PT FirKaizen Digital Solutions. Ia membangun dan mengoperasikan infrastruktur server di balik panduan ini, dan menulis berdasarkan apa yang benar-benar ia jalankan, uji, dan ukur — bukan teori.