Aller au contenu

Déployer l'observabilité LLM LangFuse sur Ubuntu 22.04 (prêt pour la production)

Monter un LangFuse durci sur Ubuntu 22.04 via Docker Compose — PostgreSQL et ClickHouse sur le réseau interne, clé de chiffrement persistée, OAuth, nginx + Let's Encrypt.

On vous demande de monter LangFuse pour que le pipeline LLM ait enfin des traces, des exécutions d’évaluations et un registre de prompts, au lieu de fouiller des journaux JSON crachés par un agent de conversation. Le démarrage rapide Docker tourne, la première trace est ingérée, l’équipe voit la latence et le coût ventilés par modèle. Six mois plus tard, l’instance ClickHouse est liée à 0.0.0.0:9000 parce que la valeur par défaut du compose n’a jamais bougé, la ENCRYPTION_KEY a été régénérée lors d’un reprovisionnement de l’hôte, donc chaque colonne de métadonnées de trace contenant un prompt client est maintenant du texte chiffré qu’on ne peut pas lire, l’endpoint d’ingestion SDK n’a aucune limitation de débit devant lui, et un worker qui s’est emballé une journée chargée a déposé 4 millions d’observations dans ClickHouse avant que quelqu’un remarque que le tableau de bord ralentissait.

Ce qui se passe

Un déploiement LangFuse qui soutient réellement un produit LLM demande beaucoup plus que docker compose up. PostgreSQL contient les lignes d’organisation, de projet, d’utilisateur et de prompts ; ClickHouse contient les tables de traces et d’observations qui croissent le plus vite. Les deux doivent rester sur le réseau compose interne — jamais publiés sur l’interface publique de l’hôte. Les conteneurs web et worker s’assoient derrière nginx avec Let’s Encrypt ; l’hôte ne doit publier que :443. La ENCRYPTION_KEY est une valeur hex de 32 octets que LangFuse utilise pour sceller les colonnes de clés API LLM et les secrets de versions de prompt — si elle change, ces lignes deviennent illisibles, et la seule récupération c’est de ressaisir manuellement chaque identifiant de modèle et d’accepter que l’historique des versions de prompt perd ses métadonnées scellées. Les endpoints d’ingestion SDK sous /api/public/ingestion acceptent des lots à haut volume et doivent être à la fois authentifiés (clé publique + secrète LangFuse par projet) et limités en débit au proxy pour qu’un worker en dérive ne puisse pas inonder ClickHouse. Le SSO OAuth remplace le couple courriel/mot de passe interne pour que l’identité chevauche l’IdP, et le compte administrateur de bootstrap est désactivé après la première connexion OAuth.

Comment vérifier

Après installation, l’hôte ne doit exposer que :443 et :22 :

ss -lntp | grep -E ':(80|443|3000|5432|8123|9000)\b'
# 0.0.0.0:443  nginx
# 127.0.0.1:3000  langfuse-web (via compose)

PostgreSQL sur 5432 et ClickHouse sur 8123/9000 ne doivent pas apparaître côté hôte. L’ingestion SDK doit rejeter les appels anonymes :

curl -sS -o /dev/null -w '%{http_code}\n' \
  -X POST https://langfuse.example.com/api/public/ingestion \
  -H 'Content-Type: application/json' -d '{"batch":[]}'
# 401

ClickHouse ne doit être joignable que depuis le worker LangFuse, et le compteur de traces doit bouger quand vous envoyez une trace de test :

docker compose -f /opt/langfuse/docker-compose.yml exec clickhouse \
  clickhouse-client --query "SELECT count() FROM traces"

Si l’endpoint d’ingestion publique retourne 200 sans Authorization: Basic, chaque invocation de modèle de votre parc est désormais inscriptible par n’importe qui qui peut atteindre l’URL.

Le correctif

Enregistrez le script ci-dessous sous /root/setup-langfuse-ubuntu22.sh, puis exécutez-le. Il installe LangFuse sur une VM Ubuntu 22.04 fraîche : mise à jour de base, UFW (SSH + HTTP + HTTPS uniquement), durcissement SSH avec conservation de l’accès clé root, unattended-upgrades, Docker CE + plugin compose, la pile compose LangFuse v3 avec PostgreSQL + ClickHouse + Redis maintenus sur le réseau interne, SALT et ENCRYPTION_KEY générés aléatoirement et écrits dans /opt/langfuse/.env en chmod 600, variables OAuth câblées pour l’IdP configuré, nginx qui termine TLS pour l’interface web et l’ingestion SDK publique avec HSTS et limitation de débit par IP sur /api/public/, Let’s Encrypt via le plugin nginx de certbot, et une boucle d’attente qui valide :3000 puis :443 avant de déclarer succès.

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

### Ubuntu 22.04 LangFuse clean VM installer
### Keeps root SSH key login enabled
### Disables SSH password login
### Enables automatic security updates
### Installs and configures Docker + LangFuse + PostgreSQL + ClickHouse + Redis + nginx + Let's Encrypt
### ENCRYPTION_KEY persisted; DB and ClickHouse internal-only; ingest rate-limited
### No local backups; assumes VM-level backup
### Reboot remains manual

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

: "${LANGFUSE_DOMAIN:?Set LANGFUSE_DOMAIN=langfuse.example.com}"
: "${LANGFUSE_EMAIL:?Set LANGFUSE_EMAIL=ops@example.com for Let's Encrypt}"
: "${OAUTH_PROVIDER:?Set OAUTH_PROVIDER=oidc (oidc|github|google)}"
: "${OAUTH_CLIENT_ID:?Set OAUTH_CLIENT_ID}"
: "${OAUTH_CLIENT_SECRET:?Set OAUTH_CLIENT_SECRET}"
OAUTH_ISSUER="${OAUTH_ISSUER:-https://sso.example.com/application/o/langfuse/}"
LANGFUSE_VERSION="${LANGFUSE_VERSION:-3.49.1}"
LANGFUSE_NEXTAUTH_SECRET="${LANGFUSE_NEXTAUTH_SECRET:-$(openssl rand -hex 32)}"
LANGFUSE_SALT="${LANGFUSE_SALT:-$(openssl rand -hex 32)}"
LANGFUSE_ENCRYPTION_KEY="${LANGFUSE_ENCRYPTION_KEY:-$(openssl rand -hex 32)}"
LANGFUSE_PG_PASSWORD="${LANGFUSE_PG_PASSWORD:-$(openssl rand -hex 24)}"
LANGFUSE_REDIS_PASSWORD="${LANGFUSE_REDIS_PASSWORD:-$(openssl rand -hex 24)}"
LANGFUSE_CLICKHOUSE_PASSWORD="${LANGFUSE_CLICKHOUSE_PASSWORD:-$(openssl rand -hex 24)}"

echo
echo "========================================"
echo "LangFuse 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 \
  software-properties-common

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

echo "==> Applying kernel/network tuning"
cat > /etc/sysctl.d/99-langfuse.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.max_map_count = 262144
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-langfuse.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 for security"
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 Docker CE"
install -m 0755 -d /etc/apt/keyrings
curl -fsSL https://download.docker.com/linux/ubuntu/gpg \
  | gpg --dearmor -o /etc/apt/keyrings/docker.gpg
chmod a+r /etc/apt/keyrings/docker.gpg
echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/ubuntu jammy stable" \
  > /etc/apt/sources.list.d/docker.list
apt-get update
apt-get -y install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin

systemctl enable --now docker

echo "==> Preparing /opt/langfuse"
mkdir -p /opt/langfuse/volumes/{pgdata,clickhouse,redis,minio,events}
chmod 700 /opt/langfuse

cat > /opt/langfuse/.env <<ENV
LANGFUSE_VERSION=${LANGFUSE_VERSION}
LANGFUSE_DOMAIN=${LANGFUSE_DOMAIN}
NEXTAUTH_SECRET=${LANGFUSE_NEXTAUTH_SECRET}
SALT=${LANGFUSE_SALT}
ENCRYPTION_KEY=${LANGFUSE_ENCRYPTION_KEY}
PG_PASSWORD=${LANGFUSE_PG_PASSWORD}
REDIS_PASSWORD=${LANGFUSE_REDIS_PASSWORD}
CLICKHOUSE_PASSWORD=${LANGFUSE_CLICKHOUSE_PASSWORD}
OAUTH_PROVIDER=${OAUTH_PROVIDER}
OAUTH_CLIENT_ID=${OAUTH_CLIENT_ID}
OAUTH_CLIENT_SECRET=${OAUTH_CLIENT_SECRET}
OAUTH_ISSUER=${OAUTH_ISSUER}
ENV

chmod 600 /opt/langfuse/.env

cat > /opt/langfuse/docker-compose.yml <<'COMPOSE'
services:
  postgres:
    image: postgres:16-alpine
    restart: unless-stopped
    environment:
      POSTGRES_USER: langfuse
      POSTGRES_PASSWORD: ${PG_PASSWORD}
      POSTGRES_DB: langfuse
    volumes:
      - /opt/langfuse/volumes/pgdata:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U langfuse -d langfuse"]
      interval: 30s
      timeout: 5s
      retries: 5
      start_period: 20s

  clickhouse:
    image: clickhouse/clickhouse-server:24.3
    restart: unless-stopped
    environment:
      CLICKHOUSE_DB: default
      CLICKHOUSE_USER: clickhouse
      CLICKHOUSE_PASSWORD: ${CLICKHOUSE_PASSWORD}
      CLICKHOUSE_DEFAULT_ACCESS_MANAGEMENT: "1"
    volumes:
      - /opt/langfuse/volumes/clickhouse:/var/lib/clickhouse
    ulimits:
      nofile:
        soft: 262144
        hard: 262144
    healthcheck:
      test: ["CMD-SHELL", "wget -qO- http://localhost:8123/ping || exit 1"]
      interval: 30s
      timeout: 5s
      retries: 5
      start_period: 30s

  redis:
    image: redis:7-alpine
    restart: unless-stopped
    command: redis-server --requirepass ${REDIS_PASSWORD} --maxmemory-policy allkeys-lru
    volumes:
      - /opt/langfuse/volumes/redis:/data
    healthcheck:
      test: ["CMD-SHELL", "redis-cli -a ${REDIS_PASSWORD} ping | grep PONG"]
      interval: 30s
      timeout: 3s
      retries: 5
      start_period: 20s

  minio:
    image: minio/minio:RELEASE.2024-08-29T01-40-52Z
    restart: unless-stopped
    command: server /data --console-address ":9001"
    environment:
      MINIO_ROOT_USER: minio
      MINIO_ROOT_PASSWORD: ${CLICKHOUSE_PASSWORD}
    volumes:
      - /opt/langfuse/volumes/minio:/data

  langfuse-worker:
    image: langfuse/langfuse-worker:${LANGFUSE_VERSION}
    restart: unless-stopped
    depends_on:
      postgres:
        condition: service_healthy
      clickhouse:
        condition: service_healthy
      redis:
        condition: service_healthy
    environment:
      DATABASE_URL: postgresql://langfuse:${PG_PASSWORD}@postgres:5432/langfuse
      CLICKHOUSE_MIGRATION_URL: clickhouse://clickhouse:9000
      CLICKHOUSE_URL: http://clickhouse:8123
      CLICKHOUSE_USER: clickhouse
      CLICKHOUSE_PASSWORD: ${CLICKHOUSE_PASSWORD}
      CLICKHOUSE_CLUSTER_ENABLED: "false"
      REDIS_HOST: redis
      REDIS_PORT: "6379"
      REDIS_AUTH: ${REDIS_PASSWORD}
      LANGFUSE_S3_EVENT_UPLOAD_BUCKET: langfuse
      LANGFUSE_S3_EVENT_UPLOAD_REGION: auto
      LANGFUSE_S3_EVENT_UPLOAD_ACCESS_KEY_ID: minio
      LANGFUSE_S3_EVENT_UPLOAD_SECRET_ACCESS_KEY: ${CLICKHOUSE_PASSWORD}
      LANGFUSE_S3_EVENT_UPLOAD_ENDPOINT: http://minio:9000
      LANGFUSE_S3_EVENT_UPLOAD_FORCE_PATH_STYLE: "true"
      SALT: ${SALT}
      ENCRYPTION_KEY: ${ENCRYPTION_KEY}
      TELEMETRY_ENABLED: "false"
      LANGFUSE_ENABLE_EXPERIMENTAL_FEATURES: "false"

  langfuse-web:
    image: langfuse/langfuse:${LANGFUSE_VERSION}
    restart: unless-stopped
    depends_on:
      postgres:
        condition: service_healthy
      clickhouse:
        condition: service_healthy
      redis:
        condition: service_healthy
    environment:
      DATABASE_URL: postgresql://langfuse:${PG_PASSWORD}@postgres:5432/langfuse
      CLICKHOUSE_MIGRATION_URL: clickhouse://clickhouse:9000
      CLICKHOUSE_URL: http://clickhouse:8123
      CLICKHOUSE_USER: clickhouse
      CLICKHOUSE_PASSWORD: ${CLICKHOUSE_PASSWORD}
      REDIS_HOST: redis
      REDIS_PORT: "6379"
      REDIS_AUTH: ${REDIS_PASSWORD}
      LANGFUSE_S3_EVENT_UPLOAD_BUCKET: langfuse
      LANGFUSE_S3_EVENT_UPLOAD_REGION: auto
      LANGFUSE_S3_EVENT_UPLOAD_ACCESS_KEY_ID: minio
      LANGFUSE_S3_EVENT_UPLOAD_SECRET_ACCESS_KEY: ${CLICKHOUSE_PASSWORD}
      LANGFUSE_S3_EVENT_UPLOAD_ENDPOINT: http://minio:9000
      LANGFUSE_S3_EVENT_UPLOAD_FORCE_PATH_STYLE: "true"
      NEXTAUTH_URL: https://${LANGFUSE_DOMAIN}
      NEXTAUTH_SECRET: ${NEXTAUTH_SECRET}
      SALT: ${SALT}
      ENCRYPTION_KEY: ${ENCRYPTION_KEY}
      TELEMETRY_ENABLED: "false"
      LANGFUSE_INIT_USER_NAME: ""
      AUTH_DISABLE_USERNAME_PASSWORD: "false"
      AUTH_DISABLE_SIGNUP: "true"
      AUTH_OAUTH_PROVIDER: ${OAUTH_PROVIDER}
      AUTH_OAUTH_CLIENT_ID: ${OAUTH_CLIENT_ID}
      AUTH_OAUTH_CLIENT_SECRET: ${OAUTH_CLIENT_SECRET}
      AUTH_OAUTH_ISSUER: ${OAUTH_ISSUER}
    ports:
      - "127.0.0.1:3000:3000"
    ulimits:
      nofile:
        soft: 64000
        hard: 64000
COMPOSE

echo "==> Starting LangFuse stack"
docker compose --env-file /opt/langfuse/.env -f /opt/langfuse/docker-compose.yml up -d

echo "==> Waiting for LangFuse web on 127.0.0.1:3000"
for i in {1..120}; do
  if ss -lntp | grep -q '127.0.0.1:3000'; then
    break
  fi
  sleep 2
done

if ! ss -lntp | grep -q '127.0.0.1:3000'; then
  echo "LangFuse web failed to listen on 127.0.0.1:3000"
  docker compose -f /opt/langfuse/docker-compose.yml logs --tail=200 langfuse-web || true
  exit 1
fi

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

cat > /etc/nginx/conf.d/langfuse-ratelimit.conf <<'RATELIMIT'
limit_req_zone $binary_remote_addr zone=langfuse_ingest:10m rate=200r/s;
RATELIMIT

cat > /etc/nginx/sites-available/langfuse <<NGINX
upstream langfuse_backend {
    server 127.0.0.1:3000;
    keepalive 32;
}

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

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

    client_max_body_size 100M;
    proxy_read_timeout   300s;
    proxy_send_timeout   300s;
    proxy_connect_timeout 60s;

    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;

    location /api/public/ {
        limit_req zone=langfuse_ingest burst=400 nodelay;
        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://langfuse_backend;
    }

    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://langfuse_backend;
    }
}
NGINX

ln -sf /etc/nginx/sites-available/langfuse /etc/nginx/sites-enabled/langfuse
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 "${LANGFUSE_EMAIL}" -d "${LANGFUSE_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 "==> Final package update"
apt-get -y upgrade

echo
echo "========================================"
echo "DONE"
echo "========================================"
echo
echo "Kernel:"
uname -r

echo
echo "SSH effective settings:"
sshd -T | grep -E '^(permitrootlogin|passwordauthentication|pubkeyauthentication) ' || true

echo
echo "Listeners:"
ss -lntp | grep -E ':(80|443|3000|5432|8123|9000)\b' || true

echo
echo "Containers:"
docker compose -f /opt/langfuse/docker-compose.yml ps

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

echo
echo "Anonymous ingest must be 401:"
curl -sS -o /dev/null -w '%{http_code}\n' \
  -X POST "https://${LANGFUSE_DOMAIN}/api/public/ingestion" \
  -H 'Content-Type: application/json' -d '{"batch":[]}' || true

echo
echo "Secrets written to /opt/langfuse/.env (mode 600). Move them to your secrets manager and remove the file from this host before going live."
echo "ENCRYPTION_KEY MUST be persisted. If you lose it, every stored LLM provider API key and every encrypted prompt-version secret is unreadable ciphertext. There is no recovery path."

echo
echo "Web UI:"
echo "https://${LANGFUSE_DOMAIN}/"

echo
echo "First steps:"
echo "1. Sign in via OAuth."
echo "2. Create a project. Generate the project public + secret keys."
echo "3. Configure the SDK with LANGFUSE_HOST=https://${LANGFUSE_DOMAIN}, the public key, and the secret key."
echo "4. Send a test trace from any SDK; confirm it appears under Traces within ~30s."

Rendez-le exécutable et exécutez-le :

chmod 700 /root/setup-langfuse-ubuntu22.sh
LANGFUSE_DOMAIN=langfuse.example.com \
LANGFUSE_EMAIL=ops@example.com \
OAUTH_PROVIDER=oidc \
OAUTH_CLIENT_ID=langfuse \
OAUTH_CLIENT_SECRET=... \
OAUTH_ISSUER=https://sso.example.com/application/o/langfuse/ \
/root/setup-langfuse-ubuntu22.sh

Ouvrez https://langfuse.example.com/ et complétez la connexion OAuth ; le premier utilisateur devient le propriétaire de l’organisation. Créez un projet, copiez la clé publique et la clé secrète dans la configuration de votre SDK, et confirmez qu’une trace de test atterrit dans la trentaine de secondes. Déplacez /opt/langfuse/.env vers votre gestionnaire de secrets et sauvegardez ENCRYPTION_KEY séparément — la perdre rend illisibles tous les identifiants de fournisseur de modèle stockés et tous les champs scellés des versions de prompt, sans chemin de récupération.

Exploitez le LangFuse de production dans un environnement infogéré par Stack Harbor, avec alertes sur les pics de coûts LLM, anomalies de débit d’ingestion et escalade Sev-1 : Supervision et soutien.