On vous demande de monter un LLM local pour que l’équipe de support cesse de coller des données clients dans un chatbot hébergé chez un tiers. Vous installez Ollama avec la commande one-liner de la documentation, vous lancez ollama pull llama3.2, la réponse arrive en quelques secondes, vous remettez ça à l’équipe. Six mois plus tard, le GPU est en OOM à la pointe parce que la fenêtre de contexte a grossi et que rien ne plafonne la concurrence, l’API est ouverte sur 0.0.0.0:11434 parce que l’unit systemd a gardé sa valeur par défaut, aucune clé d’API n’a jamais été exigée, et la boîte qui devait garder les données à l’interne se fait scraper par n’importe quel client capable d’atteindre le VLAN.
Ce qui se passe
Un déploiement Ollama réellement prêt pour la production demande beaucoup plus que l’installateur. Le serveur de modèle doit être lié à 127.0.0.1 uniquement et s’asseoir derrière nginx qui termine TLS, avec une clé d’API exigée à chaque requête sur l’endpoint compatible OpenAI /v1/chat/completions. La mémoire GPU doit avoir une marge pour le modèle choisi et sa fenêtre de contexte — un modèle 7B en fp16 demande environ 14 Go de VRAM, un 7B quantifié 4-bit tient confortablement dans 8 Go, et le cache KV pour un contexte 32k peut ajouter 4 à 8 Go selon la taille de lot. Les poids des modèles doivent vivre sur le bon disque — /var/lib/ollama sur le volume de données, pas le disque OS — parce qu’un llama3.1:70b va engloutir 40 Go et le disque OS va se remplir en silence. Le débit en tokens et la latence p95 doivent être scrapés vers le tableau de bord ; la seule chose pire qu’un LLM lent, c’est un LLM lent que personne ne voit ralentir. Et un plafond strict de concurrence côté API plus un rate limit côté nginx empêche un seul client bruyant d’affamer le reste.
Comment vérifier
Après installation, les écouteurs doivent ressembler à ça :
ss -lntp | grep -E ':(443|11434)\b'
# 0.0.0.0:443 nginx
# 127.0.0.1:11434 ollama
Le port d’Ollama doit être 127.0.0.1, jamais 0.0.0.0. Sanité GPU — le pilote doit voir la carte et ollama doit apparaître comme processus CUDA sous charge :
nvidia-smi
Aller-retour bout-en-bout via l’endpoint compatible OpenAI, clé d’API dans l’entête :
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'
Si ça retourne OK, le runtime, le GPU, nginx, TLS et le chemin clé d’API sont tous branchés correctement. Si nvidia-smi montre le modèle qui tourne sur CPU au lieu du GPU, vous avez un problème de visibilité CUDA et l’inférence sera 20 à 50 fois plus lente.
Le correctif
Enregistrez le script ci-dessous sous /root/setup-ollama-ubuntu22.sh, puis exécutez-le. Il déroule l’installation complète sur une VM Ubuntu 22.04 fraîche : mise à jour de base, ajustement noyau, limites de fichiers, UFW (SSH + HTTP + HTTPS uniquement), durcissement SSH, unattended-upgrades, pilote NVIDIA + toolkit CUDA si un GPU est présent (bascule CPU avec avertissement sinon), Ollama installé puis reconfiguré pour binder sur 127.0.0.1:11434 avec /var/lib/ollama comme magasin de modèles, une clé d’API générée, nginx en façade qui termine TLS avec vérification de l’entête Authorization, Let’s Encrypt via certbot, vérification des écouteurs, puis un téléchargement du modèle llama3.2:3b pour que le serveur soit immédiatement utilisable.
#!/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."
Rendez-le exécutable et lancez-le :
chmod 700 /root/setup-ollama-ubuntu22.sh
OLLAMA_DOMAIN=llm.example.com OLLAMA_EMAIL=ops@example.com /root/setup-ollama-ubuntu22.sh
Le script imprime la clé d’API générée à la fin — capturez-la, poussez-la dans votre gestionnaire de secrets, puis taillez le fichier site nginx pour retirer la référence en clair. Redémarrez une fois pour que le pilote NVIDIA charge proprement, puis lancez nvidia-smi pendant qu’une requête est en vol ; le processus ollama doit apparaître dans la liste des processus CUDA. Branchez nvidia_smi_exporter ou le collector GPU de node_exporter dans votre monitoring pour que l’utilisation VRAM, l’utilisation GPU et la latence d’inférence finissent sur le même tableau de bord que le reste du parc.
Faites tourner l’Ollama de production dans un environnement infogéré par Stack Harbor avec monitoring GPU-aware, cadence de mise à jour des modèles et escalade Sev-1 en place : Environnements infogérés. Si vous avez aussi besoin du GPU IaaS sous-jacent, voir Cloud Compute.