Skip to content

Deploying vLLM inference server on Ubuntu 22.04 (production-ready)

Stand up a hardened vLLM GPU server on Ubuntu 22.04 with CUDA 12.x, Python venv, systemd, Hugging Face model and OpenAI-compatible API behind nginx + Let's Encrypt.

You’ve been asked to run a real production inference tier — concurrent users, long contexts, predictable p95. You install vLLM with pip install vllm, launch the OpenAI-compatible server, the first benchmark looks great, you hand it over. Six months later the GPU OOMs every Monday morning because --max-model-len defaulted past the available KV-cache budget, the server is restarting every six hours because the systemd unit has no Restart=on-failure, the API is on 0.0.0.0:8000 with no key, and the model cache is wedged on the OS disk where the next df -h will fill the partition.

What’s happening

A vLLM deployment that is actually production-ready needs more than the pip install. PagedAttention plus tensor parallelism are why vLLM throughputs 5-10x Ollama on the same hardware, but they also mean the operator has to size three things up front: --max-model-len for the longest prompt+completion you intend to serve, --gpu-memory-utilization to leave headroom for activations and concurrent requests, and --tensor-parallel-size to match the number of GPUs the model is sharded across. A 7B model in fp16 needs ~14 GB VRAM for weights plus another ~4-8 GB for the KV cache at 8k context with reasonable batch size; a 70B in fp16 needs ~140 GB and forces tensor-parallel across 2x A100 80GB or 4x A100 40GB. The OpenAI-compatible API has to bind on 127.0.0.1 behind nginx with an API key, the Hugging Face model cache has to live on /var/lib/vllm on the data volume, and the systemd unit has to restart on failure with LimitNOFILE=64000 so the asyncio worker pool can scale.

How to verify

After install, the listeners should look like this:

ss -lntp | grep -E ':(443|8000)\b'
# 0.0.0.0:443     nginx
# 127.0.0.1:8000  vllm (uvicorn)

The vLLM port must be 127.0.0.1, never 0.0.0.0. GPU memory should show the model loaded with reasonable headroom:

nvidia-smi --query-gpu=name,memory.used,memory.total,utilization.gpu --format=csv

End-to-end round trip via the OpenAI-compatible endpoint:

curl -fsS -X POST https://llm.example.com/v1/chat/completions \
  -H "Authorization: Bearer ${VLLM_API_KEY}" \
  -H "Content-Type: application/json" \
  -d '{"model":"meta-llama/Llama-3.1-8B-Instruct","messages":[{"role":"user","content":"reply OK"}],"max_tokens":4}' \
  | jq -r '.choices[0].message.content'

If the response is OK and nvidia-smi shows the vllm worker holding stable VRAM, the runtime is live. If memory usage climbs across requests without flattening, your --gpu-memory-utilization is too aggressive and the next long-context prompt will OOM.

The fix

Save the script below as /root/setup-vllm-ubuntu22.sh, then run it. It runs the installer flow on a fresh Ubuntu 22.04 VM: base update, kernel tuning, file limits, UFW, SSH hardening, unattended-upgrades, NVIDIA driver 535 + CUDA 12.4 toolkit if a GPU is present (CPU fallback with a warning), a Python 3.11 venv at /opt/vllm/venv with vLLM and its CUDA wheels installed, /var/lib/vllm as the Hugging Face cache, a dedicated vllm system user, a systemd unit that runs vllm serve with commented --max-model-len / --tensor-parallel-size / --gpu-memory-utilization knobs so the operator can tune, nginx terminating TLS with API-key check and Let’s Encrypt, and listener verification.

#!/usr/bin/env bash
set -euo pipefail

### Ubuntu 22.04 vLLM clean VM installer
### Installs NVIDIA driver + CUDA 12.4 if a GPU is present, CPU fallback otherwise
### Binds vLLM on 127.0.0.1 only; nginx terminates TLS and enforces API key
### Operator must set VLLM_MODEL and tune --max-model-len / --tensor-parallel-size
### No local backups; assumes VM-level backup. Model weights re-pullable from Hugging Face.
### Reboot remains manual

if [[ "$(id -u)" -ne 0 ]]; then
  echo "Run as root."
  exit 1
fi

: "${VLLM_DOMAIN:?Set VLLM_DOMAIN=llm.example.com}"
: "${VLLM_EMAIL:?Set VLLM_EMAIL=ops@example.com for Let's Encrypt}"
VLLM_API_KEY="${VLLM_API_KEY:-$(openssl rand -hex 32)}"
VLLM_MODEL="${VLLM_MODEL:-meta-llama/Llama-3.1-8B-Instruct}"
VLLM_MAX_MODEL_LEN="${VLLM_MAX_MODEL_LEN:-8192}"
VLLM_TP_SIZE="${VLLM_TP_SIZE:-1}"
VLLM_GPU_MEM_UTIL="${VLLM_GPU_MEM_UTIL:-0.90}"
VLLM_DTYPE="${VLLM_DTYPE:-auto}"
VLLM_HF_TOKEN="${VLLM_HF_TOKEN:-}"
VLLM_HOME="/opt/vllm"
VLLM_CACHE="/var/lib/vllm"

echo
echo "========================================"
echo "vLLM Ubuntu 22.04 Setup"
echo "========================================"
echo

echo "==> Updating base OS"
export DEBIAN_FRONTEND=noninteractive
apt-get update
apt-get -y upgrade

echo "==> Installing base packages"
apt-get -y install \
  vim curl wget ca-certificates gnupg2 \
  chrony fail2ban unattended-upgrades \
  ufw lsof tcpdump dnsutils tar gzip \
  iproute2 net-tools openssl jq pciutils \
  build-essential git \
  software-properties-common

echo "==> Enabling time sync"
systemctl enable --now chrony
timedatectl set-ntp true

echo "==> Detecting NVIDIA GPU"
HAS_GPU=0
if lspci | grep -qi 'nvidia'; then
  HAS_GPU=1
  echo "NVIDIA GPU detected."
else
  echo "WARNING: no NVIDIA GPU detected. vLLM will run in CPU mode (very slow, only suitable for smoke tests)."
fi

if [[ $HAS_GPU -eq 1 ]]; then
  echo "==> Installing NVIDIA driver 535 and CUDA 12.4 toolkit"
  apt-get -y install ubuntu-drivers-common
  ubuntu-drivers autoinstall || apt-get -y install nvidia-driver-535

  wget -qO /tmp/cuda-keyring.deb \
    https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2204/x86_64/cuda-keyring_1.1-1_all.deb
  dpkg -i /tmp/cuda-keyring.deb
  apt-get update
  apt-get -y install cuda-toolkit-12-4

  if ! grep -q '/usr/local/cuda/bin' /etc/profile.d/cuda.sh 2>/dev/null; then
    cat > /etc/profile.d/cuda.sh <<'CUDAENV'
export PATH=/usr/local/cuda/bin:$PATH
export LD_LIBRARY_PATH=/usr/local/cuda/lib64:$LD_LIBRARY_PATH
CUDAENV
  fi
fi

echo "==> Applying kernel/network tuning"
cat > /etc/sysctl.d/99-vllm.conf <<'SYSCTL'
net.core.default_qdisc = fq
net.ipv4.tcp_congestion_control = bbr

net.core.somaxconn = 4096
net.core.netdev_max_backlog = 250000
net.ipv4.tcp_max_syn_backlog = 8192
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_fin_timeout = 15
net.ipv4.ip_local_port_range = 10240 65535

net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.default.accept_redirects = 0
net.ipv6.conf.all.accept_redirects = 0
net.ipv6.conf.default.accept_redirects = 0
net.ipv4.conf.all.send_redirects = 0
net.ipv4.conf.default.send_redirects = 0

kernel.dmesg_restrict = 1
kernel.kptr_restrict = 2
fs.file-max = 2097152
vm.swappiness = 10
vm.overcommit_memory = 1
SYSCTL

modprobe tcp_bbr || true
echo tcp_bbr > /etc/modules-load.d/bbr.conf
sysctl --system

echo "==> Setting file limits"
cat > /etc/security/limits.d/99-vllm.conf <<'LIMITS'
* soft nofile 64000
* hard nofile 64000
root soft nofile 64000
root hard nofile 64000
LIMITS

echo "==> Configuring UFW"
ufw --force reset
ufw default deny incoming
ufw default allow outgoing
ufw allow 22/tcp
ufw allow 80/tcp
ufw allow 443/tcp
ufw --force enable

echo "==> Hardening SSH while keeping root SSH key login enabled"
cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak.$(date +%F-%H%M%S)

set_sshd_option() {
  local key="$1"
  local value="$2"
  if grep -qE "^[#[:space:]]*${key}[[:space:]]+" /etc/ssh/sshd_config; then
    sed -i "s|^[#[:space:]]*${key}[[:space:]].*|${key} ${value}|" /etc/ssh/sshd_config
  else
    echo "${key} ${value}" >> /etc/ssh/sshd_config
  fi
}

set_sshd_option PermitRootLogin prohibit-password
set_sshd_option PasswordAuthentication no
set_sshd_option PubkeyAuthentication yes
set_sshd_option KbdInteractiveAuthentication no
set_sshd_option ChallengeResponseAuthentication no
set_sshd_option X11Forwarding no
set_sshd_option ClientAliveInterval 300
set_sshd_option ClientAliveCountMax 2
set_sshd_option MaxAuthTries 4

sshd -t
systemctl restart ssh

echo "==> Configuring fail2ban"
mkdir -p /etc/fail2ban/jail.d
cat > /etc/fail2ban/jail.d/sshd.local <<'FAIL2BAN'
[sshd]
enabled = true
port = ssh
backend = systemd
maxretry = 4
findtime = 10m
bantime = 1h
FAIL2BAN

systemctl enable --now fail2ban

echo "==> Configuring unattended-upgrades"
cat > /etc/apt/apt.conf.d/20auto-upgrades <<'AUTOUPG'
APT::Periodic::Update-Package-Lists "1";
APT::Periodic::Unattended-Upgrade "1";
APT::Periodic::AutocleanInterval "7";
AUTOUPG

echo "==> Installing Python 3.11"
add-apt-repository -y ppa:deadsnakes/ppa
apt-get update
apt-get -y install python3.11 python3.11-venv python3.11-dev

echo "==> Creating vllm system user"
if ! id vllm >/dev/null 2>&1; then
  useradd --system --create-home --home-dir "${VLLM_HOME}" --shell /usr/sbin/nologin vllm
fi

echo "==> Preparing model cache on data volume"
mkdir -p "${VLLM_CACHE}"
chown -R vllm:vllm "${VLLM_CACHE}" "${VLLM_HOME}"
chmod 750 "${VLLM_CACHE}"

echo "==> Creating Python venv and installing vLLM"
sudo -u vllm python3.11 -m venv "${VLLM_HOME}/venv"
sudo -u vllm "${VLLM_HOME}/venv/bin/pip" install --upgrade pip wheel setuptools
sudo -u vllm "${VLLM_HOME}/venv/bin/pip" install vllm

echo "==> Writing environment file"
cat > /etc/default/vllm <<VLLMENV
# vLLM runtime environment
# Tune these for the model and the GPU:
#   VLLM_MODEL            - Hugging Face model id
#   VLLM_MAX_MODEL_LEN    - max prompt+completion tokens (drives KV cache size)
#   VLLM_TP_SIZE          - tensor-parallel-size (set to number of GPUs)
#   VLLM_GPU_MEM_UTIL     - fraction of VRAM vLLM may use (0.85-0.92 typical)
#   VLLM_DTYPE            - auto | float16 | bfloat16 | float32
VLLM_MODEL=${VLLM_MODEL}
VLLM_MAX_MODEL_LEN=${VLLM_MAX_MODEL_LEN}
VLLM_TP_SIZE=${VLLM_TP_SIZE}
VLLM_GPU_MEM_UTIL=${VLLM_GPU_MEM_UTIL}
VLLM_DTYPE=${VLLM_DTYPE}
VLLM_API_KEY=${VLLM_API_KEY}
HF_HOME=${VLLM_CACHE}
HF_HUB_CACHE=${VLLM_CACHE}
HUGGING_FACE_HUB_TOKEN=${VLLM_HF_TOKEN}
VLLMENV

chmod 600 /etc/default/vllm
chown root:vllm /etc/default/vllm
chmod 640 /etc/default/vllm

echo "==> Writing systemd unit for vLLM"
cat > /etc/systemd/system/vllm.service <<'VLLM_UNIT'
[Unit]
Description=vLLM OpenAI-compatible inference server
After=network.target
Wants=network-online.target

[Service]
Type=simple
User=vllm
Group=vllm
EnvironmentFile=/etc/default/vllm
WorkingDirectory=/opt/vllm
ExecStart=/opt/vllm/venv/bin/vllm serve ${VLLM_MODEL} \
  --host 127.0.0.1 \
  --port 8000 \
  --api-key ${VLLM_API_KEY} \
  --max-model-len ${VLLM_MAX_MODEL_LEN} \
  --tensor-parallel-size ${VLLM_TP_SIZE} \
  --gpu-memory-utilization ${VLLM_GPU_MEM_UTIL} \
  --dtype ${VLLM_DTYPE} \
  --disable-log-requests
Restart=on-failure
RestartSec=10
TimeoutStartSec=600
LimitNOFILE=64000

[Install]
WantedBy=multi-user.target
VLLM_UNIT

systemctl daemon-reload
systemctl enable vllm

echo "==> Starting vLLM (first run will download model weights; this can take 10-30 minutes)"
systemctl start vllm

echo "==> Waiting for vLLM on 127.0.0.1:8000 (long timeout for first model download)"
for i in {1..180}; do
  if ss -lntp | grep -q '127.0.0.1:8000'; then
    break
  fi
  sleep 10
done

if ! ss -lntp | grep -q '127.0.0.1:8000'; then
  echo "vLLM failed to listen on 127.0.0.1:8000 within 30 minutes"
  systemctl status vllm --no-pager -l || true
  journalctl -u vllm -n 300 --no-pager || true
  exit 1
fi

echo "==> Installing nginx and certbot"
apt-get -y install nginx certbot python3-certbot-nginx

cat > /etc/nginx/conf.d/vllm-ratelimit.conf <<'RATELIMIT'
limit_req_zone $binary_remote_addr zone=vllm_rl:10m rate=10r/s;
limit_conn_zone $binary_remote_addr zone=vllm_conn:10m;
RATELIMIT

cat > /etc/nginx/sites-available/vllm <<NGINX
upstream vllm_backend {
    server 127.0.0.1:8000;
    keepalive 32;
}

server {
    listen 80;
    listen [::]:80;
    server_name ${VLLM_DOMAIN};
    return 301 https://\$host\$request_uri;
}

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name ${VLLM_DOMAIN};

    client_max_body_size 32M;
    proxy_read_timeout   600s;
    proxy_send_timeout   600s;
    proxy_connect_timeout 60s;
    proxy_buffering      off;

    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
    add_header X-Content-Type-Options nosniff always;
    add_header X-Frame-Options SAMEORIGIN always;
    add_header Referrer-Policy strict-origin-when-cross-origin always;

    limit_req zone=vllm_rl burst=20 nodelay;
    limit_conn vllm_conn 8;

    location / {
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto \$scheme;
        proxy_http_version 1.1;
        proxy_pass http://vllm_backend;
    }
}
NGINX

ln -sf /etc/nginx/sites-available/vllm /etc/nginx/sites-enabled/vllm
rm -f /etc/nginx/sites-enabled/default

nginx -t
systemctl enable --now nginx
systemctl reload nginx

echo "==> Requesting Let's Encrypt certificate"
certbot --nginx --non-interactive --agree-tos \
  -m "${VLLM_EMAIL}" -d "${VLLM_DOMAIN}" --redirect

systemctl enable --now certbot.timer

echo "==> Waiting for HTTPS listener"
for i in {1..30}; do
  if ss -lntp | grep -q ':443'; then
    break
  fi
  sleep 1
done

echo "==> First chat completion smoke test"
curl -fsS -X POST "https://${VLLM_DOMAIN}/v1/chat/completions" \
  -H "Authorization: Bearer ${VLLM_API_KEY}" \
  -H "Content-Type: application/json" \
  -d "{\"model\":\"${VLLM_MODEL}\",\"messages\":[{\"role\":\"user\",\"content\":\"reply with the single word OK\"}],\"max_tokens\":4}" \
  | jq -r '.choices[0].message.content' || true

echo
echo "========================================"
echo "DONE"
echo "========================================"
echo

if [[ $HAS_GPU -eq 1 ]] && command -v nvidia-smi >/dev/null 2>&1; then
  echo "GPU:"
  nvidia-smi --query-gpu=name,memory.total,memory.free,utilization.gpu,driver_version --format=csv,noheader || true
else
  echo "GPU: none detected. CPU-only mode."
fi

echo
echo "Listeners:"
ss -lntp | grep -E ':(80|443|8000)\b' || true

echo
echo "Services:"
systemctl is-active vllm nginx fail2ban chrony || true

echo
echo "Model served:"
echo "${VLLM_MODEL}"
echo "  --max-model-len ${VLLM_MAX_MODEL_LEN}"
echo "  --tensor-parallel-size ${VLLM_TP_SIZE}"
echo "  --gpu-memory-utilization ${VLLM_GPU_MEM_UTIL}"

echo
echo "API URL:"
echo "https://${VLLM_DOMAIN}/v1/chat/completions"
echo
echo "API key (Authorization: Bearer ...):"
echo "${VLLM_API_KEY}"
echo
echo "Tuning lives in /etc/default/vllm. To change the model or context length, edit that file then 'systemctl restart vllm'."

echo
echo "Final step:"
echo "Reboot once so the NVIDIA driver loads cleanly, then watch 'journalctl -u vllm -f' on the first real workload to confirm KV cache fits."

Make it executable and run it:

chmod 700 /root/setup-vllm-ubuntu22.sh
VLLM_DOMAIN=llm.example.com VLLM_EMAIL=ops@example.com \
  VLLM_MODEL=meta-llama/Llama-3.1-8B-Instruct \
  VLLM_HF_TOKEN=hf_xxx \
  /root/setup-vllm-ubuntu22.sh

First boot downloads the model into /var/lib/vllm — for an 8B fp16 model expect ~16 GB, for a 70B expect ~140 GB. The systemd unit reads everything from /etc/default/vllm; to switch model or context length, edit that file and systemctl restart vllm. Track GPU memory, GPU utilization and request latency with dcgm_exporter or nvidia_gpu_exporter so the same dashboard that catches a noisy neighbour catches a KV-cache regression.

Run the production vLLM on a Stack Harbor-managed environment with GPU-aware monitoring, model patching cadence, and Sev-1 escalation in place: Managed Cloud Ops. The managed-runtime angle (vLLM as a PaaS endpoint your apps consume) is covered under Cloud PaaS.