You’ve been asked to stand up a local LLM so the support team can stop pasting customer data into hosted chat. You install Ollama with the one-liner from the docs, ollama pull llama3.2, the prompt comes back in seconds, you hand it over. Six months later the GPU is OOM at peak because the context window grew and nothing capped concurrency, the API is open on 0.0.0.0:11434 because the systemd unit kept its default, no API key was ever required, and the box that was meant to keep data on-prem is being scraped by anyone who can reach the VLAN.
What’s happening
An Ollama deployment that is actually production-ready needs more than the installer. The model server has to bind to 127.0.0.1 only and sit behind nginx terminating TLS, with an API key required on every request to the OpenAI-compatible /v1/chat/completions endpoint. GPU memory has to have headroom for the chosen model and its context window — a 7B model in fp16 needs roughly 14 GB VRAM, a 4-bit quantized 7B fits comfortably in 8 GB, and the KV cache for a 32k context can add another 4-8 GB depending on batch size. Model weights have to live on the right disk — /var/lib/ollama on the data volume, not the OS disk — because pulling llama3.1:70b will eat 40 GB and the OS disk will fill silently. Token throughput and p95 latency have to be scraped into the dashboard; the only thing worse than a slow LLM is a slow LLM that nobody notices is slow. And a hard concurrency cap on the API plus a rate limit on nginx keeps a single noisy client from starving the rest.
How to verify
After install, the listeners should look like this:
ss -lntp | grep -E ':(443|11434)\b'
# 0.0.0.0:443 nginx
# 127.0.0.1:11434 ollama
The Ollama port must be 127.0.0.1, never 0.0.0.0. GPU sanity check — the driver should see the card and ollama should show as a CUDA process under load:
nvidia-smi
End-to-end round trip via the OpenAI-compatible endpoint with the API key in the header:
curl -fsS -X POST https://llm.example.com/v1/chat/completions \
-H "Authorization: Bearer ${OLLAMA_API_KEY}" \
-H "Content-Type: application/json" \
-d '{"model":"llama3.2:3b","messages":[{"role":"user","content":"reply with the single word OK"}],"max_tokens":4}' \
| jq -r '.choices[0].message.content'
If that returns OK, the runtime, GPU, nginx, TLS and API-key path are all wired correctly. If nvidia-smi shows the model on CPU instead of GPU, you have a CUDA visibility problem and inference will be 20-50x slower.
The fix
Save the script below as /root/setup-ollama-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 + HTTP + HTTPS only), SSH hardening, unattended-upgrades, NVIDIA driver + CUDA toolkit if a GPU is present (CPU fallback with a warning if not), Ollama installed and reconfigured to bind on 127.0.0.1:11434 with /var/lib/ollama as the model store, a generated API key, nginx in front terminating TLS with an Authorization header check, Let’s Encrypt via certbot, listener verification, then a llama3.2:3b model pull so the server is immediately usable.
#!/usr/bin/env bash
set -euo pipefail
### Ubuntu 22.04 Ollama clean VM installer
### Installs NVIDIA driver + CUDA if a GPU is present, CPU fallback otherwise
### Binds Ollama on 127.0.0.1 only; nginx terminates TLS and enforces API key
### Pulls llama3.2:3b at the end so the server is immediately usable
### No local backups; assumes VM-level backup. Model weights re-pullable from upstream.
### Reboot remains manual
if [[ "$(id -u)" -ne 0 ]]; then
echo "Run as root."
exit 1
fi
: "${OLLAMA_DOMAIN:?Set OLLAMA_DOMAIN=llm.example.com}"
: "${OLLAMA_EMAIL:?Set OLLAMA_EMAIL=ops@example.com for Let's Encrypt}"
OLLAMA_API_KEY="${OLLAMA_API_KEY:-$(openssl rand -hex 32)}"
OLLAMA_MODELS_DIR="${OLLAMA_MODELS_DIR:-/var/lib/ollama}"
OLLAMA_DEFAULT_MODEL="${OLLAMA_DEFAULT_MODEL:-llama3.2:3b}"
OLLAMA_MAX_LOADED="${OLLAMA_MAX_LOADED:-1}"
OLLAMA_NUM_PARALLEL="${OLLAMA_NUM_PARALLEL:-2}"
echo
echo "========================================"
echo "Ollama 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 \
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. Falling back to CPU. Inference will be 20-50x slower and unsuitable for production with models larger than ~3B."
fi
if [[ $HAS_GPU -eq 1 ]]; then
echo "==> Installing NVIDIA driver and CUDA toolkit"
apt-get -y install ubuntu-drivers-common
ubuntu-drivers autoinstall || apt-get -y install nvidia-driver-535
distribution=$(. /etc/os-release; echo "$ID$VERSION_ID")
curl -fsSL https://nvidia.github.io/libnvidia-container/gpgkey \
| gpg --dearmor -o /usr/share/keyrings/nvidia-container-toolkit-keyring.gpg
curl -fsSL "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' \
> /etc/apt/sources.list.d/nvidia-container-toolkit.list
apt-get update
apt-get -y install nvidia-container-toolkit nvidia-cuda-toolkit
fi
echo "==> Applying kernel/network tuning"
cat > /etc/sysctl.d/99-ollama.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
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-ollama.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 Ollama"
curl -fsSL https://ollama.com/install.sh | sh
echo "==> Preparing model directory on data volume"
mkdir -p "${OLLAMA_MODELS_DIR}"
if id ollama >/dev/null 2>&1; then
chown -R ollama:ollama "${OLLAMA_MODELS_DIR}"
fi
chmod 750 "${OLLAMA_MODELS_DIR}"
echo "==> Rebinding Ollama to 127.0.0.1 and pinning model directory"
mkdir -p /etc/systemd/system/ollama.service.d
cat > /etc/systemd/system/ollama.service.d/override.conf <<OLLAMA_OVERRIDE
[Service]
Environment="OLLAMA_HOST=127.0.0.1:11434"
Environment="OLLAMA_MODELS=${OLLAMA_MODELS_DIR}"
Environment="OLLAMA_KEEP_ALIVE=5m"
Environment="OLLAMA_MAX_LOADED_MODELS=${OLLAMA_MAX_LOADED}"
Environment="OLLAMA_NUM_PARALLEL=${OLLAMA_NUM_PARALLEL}"
LimitNOFILE=64000
OLLAMA_OVERRIDE
systemctl daemon-reload
systemctl enable --now ollama
systemctl restart ollama
echo "==> Waiting for Ollama on 127.0.0.1:11434"
for i in {1..60}; do
if ss -lntp | grep -q '127.0.0.1:11434'; then
break
fi
sleep 2
done
if ! ss -lntp | grep -q '127.0.0.1:11434'; then
echo "Ollama failed to listen on 127.0.0.1:11434"
systemctl status ollama --no-pager -l || true
journalctl -u ollama -n 200 --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/ollama-ratelimit.conf <<'RATELIMIT'
limit_req_zone $binary_remote_addr zone=ollama_rl:10m rate=10r/s;
limit_conn_zone $binary_remote_addr zone=ollama_conn:10m;
RATELIMIT
cat > /etc/nginx/sites-available/ollama <<NGINX
upstream ollama_backend {
server 127.0.0.1:11434;
keepalive 32;
}
map \$http_authorization \$ollama_authorized {
default 0;
"Bearer ${OLLAMA_API_KEY}" 1;
}
server {
listen 80;
listen [::]:80;
server_name ${OLLAMA_DOMAIN};
return 301 https://\$host\$request_uri;
}
server {
listen 443 ssl http2;
listen [::]:443 ssl http2;
server_name ${OLLAMA_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=ollama_rl burst=20 nodelay;
limit_conn ollama_conn 8;
location / {
if (\$ollama_authorized = 0) {
return 401;
}
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://ollama_backend;
}
}
NGINX
ln -sf /etc/nginx/sites-available/ollama /etc/nginx/sites-enabled/ollama
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 "${OLLAMA_EMAIL}" -d "${OLLAMA_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 "==> Pulling default model ${OLLAMA_DEFAULT_MODEL}"
sudo -u ollama OLLAMA_HOST=127.0.0.1:11434 OLLAMA_MODELS=${OLLAMA_MODELS_DIR} \
ollama pull "${OLLAMA_DEFAULT_MODEL}" || \
ollama pull "${OLLAMA_DEFAULT_MODEL}"
echo "==> First chat completion smoke test"
curl -fsS -X POST "https://${OLLAMA_DOMAIN}/v1/chat/completions" \
-H "Authorization: Bearer ${OLLAMA_API_KEY}" \
-H "Content-Type: application/json" \
-d "{\"model\":\"${OLLAMA_DEFAULT_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,driver_version --format=csv,noheader || true
else
echo "GPU: none detected. CPU-only mode."
fi
echo
echo "Listeners:"
ss -lntp | grep -E ':(80|443|11434)\b' || true
echo
echo "Services:"
systemctl is-active ollama nginx fail2ban chrony || true
echo
echo "Models installed:"
ollama list || true
echo
echo "API URL:"
echo "https://${OLLAMA_DOMAIN}/v1/chat/completions"
echo
echo "API key (Authorization: Bearer ...):"
echo "${OLLAMA_API_KEY}"
echo
echo "Store the key in your secrets manager. The on-disk reference lives in /etc/nginx/sites-available/ollama (mode 644 by default — chmod it down or remove after capture)."
echo
echo "Final step:"
echo "Reboot once so the NVIDIA driver loads cleanly, then re-run 'nvidia-smi' to confirm 'ollama' is listed as a CUDA process during inference."
Make it executable and run it:
chmod 700 /root/setup-ollama-ubuntu22.sh
OLLAMA_DOMAIN=llm.example.com OLLAMA_EMAIL=ops@example.com /root/setup-ollama-ubuntu22.sh
The script prints the generated API key at the end — capture it, push it into your secrets manager, then trim the nginx site file to remove the inline reference. Reboot once so the NVIDIA driver loads cleanly, then run nvidia-smi while a request is in flight; the ollama process should appear in the CUDA processes table. Wire nvidia_smi_exporter or the node_exporter GPU collector into your monitoring so VRAM usage, GPU utilization and inference latency end up on the same dashboard as the rest of the fleet.
Run the production Ollama on a Stack Harbor-managed environment with GPU-aware monitoring, model patching cadence, and Sev-1 escalation in place: Managed Cloud Ops. If you also need the underlying GPU IaaS, see Cloud Compute.