Aller au contenu

Déployer Sentry auto-hébergé sur Ubuntu 22.04 (prêt pour la production)

Monter la pile officielle getsentry/self-hosted sur Ubuntu 22.04 — Postgres, Redis, ClickHouse via Docker Compose, nginx + Let's Encrypt, câblage SMTP.

Vous avez suivi le README de getsentry/self-hosted, lancé install.sh, posé un mot de passe admin, capturé un premier événement — fait en un après-midi. Six mois plus tard, le volume qui porte ClickHouse est à 92 %, l’installation n’a pas été mise à jour au-delà de sa version mineure parce que le chemin de mise à jour demande de lire des notes de release que personne n’a, le câblage SMTP est resté sur la valeur placeholder par défaut donc les alertes d’issue n’ont jamais atteint personne, et l’interface web est exposée sur le port 9000 depuis l’Internet public parce que l’équipe n’a jamais mis nginx devant. La pile tourne. Personne n’y fait confiance.

Ce qui se passe

Sentry auto-hébergé est une pile Docker Compose — web, worker, cron, relay, plus Postgres, Redis, Kafka, ClickHouse — et la traiter comme un seul conteneur est le bug. La pile compose doit tourner derrière un reverse proxy sur un domaine avec un vrai certificat TLS (la protection CSRF de Sentry mord dès qu’on la met derrière un proxy sans poser system.url-prefix). Le courriel a besoin d’un relais SMTP fonctionnel sinon le pipeline d’alerte d’issue est cassé en silence. La rétention ClickHouse se règle par projet dans l’interface, mais la rétention de partition dans l’env docker-compose, c’est ce qui libère réellement le disque. Les mises à jour se font version par version via le script install.sh — sauter une release n’est pas supporté. Rien de tout cela n’est exotique si vous l’avez opéré ; c’est un cimetière si vous traitez le script d’installation comme la totalité du travail.

Comment vérifier

Après avoir levé la pile, les quatre services de données doivent tourner et le service web doit répondre localement :

docker compose ps | grep -E '(web|worker|relay|postgres|redis|clickhouse)'

Sentry expose un endpoint de santé qui doit retourner du JSON, pas un 502 :

curl -s http://127.0.0.1:9000/_health/
# {"healthy": true, "problems": []}

Le premier send-test vérifie que le relay accepte l’ingest. Depuis n’importe quel hôte :

sentry-cli --url https://sentry.example.com send-event -m "self-test from $(hostname)"

Si le port 9000 est lié à 0.0.0.0 et que le pare-feu ne le bloque pas, l’installation est publique — corrigez ça avant d’émettre le premier DSN.

Le correctif

Enregistrez le script ci-dessous sous /root/setup-sentry-ubuntu2204.sh, puis exécutez-le. Il déroule l’installation complète sur une VM Ubuntu 22.04 fraîche avec au moins 8 Go RAM et 64 Go d’espace libre (les minimums officiels de la pile auto-hébergée) : mise à jour de base, UFW, durcissement SSH (clé root conservée, mot de passe désactivé), unattended-upgrades pour la sécurité, moteur Docker + plugin compose depuis le dépôt Docker amont, un clone de getsentry/self-hosted épinglé sur un tag 24.x courant, un .env généré avec clé secrète + SMTP + system.url-prefix, install.sh lancé en non-interactif, nginx + certbot pour l’interface externe, et LimitNOFILE=64000 sur Docker. Le script attend que le conteneur web passe en santé avant de continuer.

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

### Ubuntu 22.04 Sentry self-hosted clean VM installer
### Pins getsentry/self-hosted to a 24.x release tag
### Docker Compose stack: web, worker, cron, relay + Postgres/Redis/ClickHouse/Kafka
### Web listens on 127.0.0.1:9000; only nginx is public
### TLS via Let's Encrypt
### Keeps root SSH key login; disables password auth
### No local backups; assumes VM-level backup
### Minimum: 4 vCPU, 8 GB RAM, 64 GB disk

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

: "${SENTRY_DOMAIN:?Set SENTRY_DOMAIN, e.g. sentry.example.com}"
: "${SENTRY_EMAIL:?Set SENTRY_EMAIL for Let's Encrypt}"
: "${SENTRY_ADMIN_EMAIL:?Set SENTRY_ADMIN_EMAIL for the initial superuser}"
: "${SMTP_HOST:?Set SMTP_HOST}"
: "${SMTP_PORT:?Set SMTP_PORT, e.g. 587}"
: "${SMTP_USER:?Set SMTP_USER}"
: "${SMTP_PASS:?Set SMTP_PASS}"
: "${SMTP_FROM:?Set SMTP_FROM, e.g. sentry@example.com}"

SENTRY_VERSION="${SENTRY_VERSION:-24.10.0}"

echo
echo "========================================"
echo "Sentry self-hosted Ubuntu 22.04 Setup"
echo "Domain: $SENTRY_DOMAIN"
echo "Version: $SENTRY_VERSION"
echo "========================================"
echo

export DEBIAN_FRONTEND=noninteractive

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

echo "==> Installing base packages"
apt-get -y install \
  curl wget git ca-certificates gnupg \
  chrony fail2ban unattended-upgrades \
  lsof tcpdump dnsutils iproute2 net-tools jq \
  nginx \
  ufw

systemctl enable --now chronyd 2>/dev/null || systemctl enable --now chrony

echo "==> sysctl + file limits"
cat > /etc/sysctl.d/99-sentry.conf <<'SYSCTL'
net.core.somaxconn = 4096
net.core.netdev_max_backlog = 250000
net.ipv4.tcp_max_syn_backlog = 8192
net.ipv4.tcp_syncookies = 1
fs.file-max = 2097152
fs.inotify.max_user_watches = 524288
vm.max_map_count = 262144
kernel.dmesg_restrict = 1
SYSCTL
sysctl --system

cat > /etc/security/limits.d/99-sentry.conf <<'LIMITS'
* soft nofile 64000
* hard nofile 64000
LIMITS

echo "==> Hardening SSH (keep root key)"
cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak.$(date +%F-%H%M%S)
set_sshd() {
  local k="$1" v="$2"
  if grep -qE "^[#[:space:]]*${k}[[:space:]]+" /etc/ssh/sshd_config; then
    sed -i "s|^[#[:space:]]*${k}[[:space:]].*|${k} ${v}|" /etc/ssh/sshd_config
  else
    echo "${k} ${v}" >> /etc/ssh/sshd_config
  fi
}
set_sshd PermitRootLogin prohibit-password
set_sshd PasswordAuthentication no
set_sshd PubkeyAuthentication yes
set_sshd KbdInteractiveAuthentication no
set_sshd X11Forwarding no
set_sshd ClientAliveInterval 300
set_sshd MaxAuthTries 4
sshd -t
systemctl restart ssh

echo "==> fail2ban + unattended-upgrades"
cat > /etc/fail2ban/jail.d/sshd.local <<'F2B'
[sshd]
enabled = true
port = ssh
backend = systemd
maxretry = 4
findtime = 10m
bantime = 1h
F2B
systemctl enable --now fail2ban

cat > /etc/apt/apt.conf.d/20auto-upgrades <<'AUTO'
APT::Periodic::Update-Package-Lists "1";
APT::Periodic::Unattended-Upgrade "1";
AUTO
systemctl enable --now unattended-upgrades

echo "==> UFW: 22, 80, 443 only"
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 "==> Installing Docker engine + compose plugin"
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 $(. /etc/os-release && echo $VERSION_CODENAME) 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

mkdir -p /etc/systemd/system/docker.service.d
cat > /etc/systemd/system/docker.service.d/limits.conf <<'DLIM'
[Service]
LimitNOFILE=64000
DLIM
systemctl daemon-reload
systemctl enable --now docker

echo "==> Cloning getsentry/self-hosted @ ${SENTRY_VERSION}"
mkdir -p /opt
cd /opt
if [[ ! -d /opt/self-hosted ]]; then
  git clone https://github.com/getsentry/self-hosted.git
fi
cd /opt/self-hosted
git fetch --tags
git checkout "${SENTRY_VERSION}"

echo "==> Generating .env"
SENTRY_SECRET_KEY="$(openssl rand -hex 32)"

cat > /opt/self-hosted/.env.custom <<ENV
SENTRY_EVENT_RETENTION_DAYS=90
SENTRY_BIND=127.0.0.1:9000
SENTRY_IMAGE=getsentry/sentry:${SENTRY_VERSION}
SNUBA_IMAGE=getsentry/snuba:${SENTRY_VERSION}
RELAY_IMAGE=getsentry/relay:${SENTRY_VERSION}
SYMBOLICATOR_IMAGE=getsentry/symbolicator:${SENTRY_VERSION}
COMPOSE_PROFILES=feature-complete
ENV

if [[ ! -f /opt/self-hosted/.env ]]; then
  cp /opt/self-hosted/.env.example /opt/self-hosted/.env 2>/dev/null || touch /opt/self-hosted/.env
fi

update_env() {
  local k="$1" v="$2"
  if grep -qE "^${k}=" /opt/self-hosted/.env; then
    sed -i "s|^${k}=.*|${k}=${v}|" /opt/self-hosted/.env
  else
    echo "${k}=${v}" >> /opt/self-hosted/.env
  fi
}

update_env SENTRY_SECRET_KEY        "${SENTRY_SECRET_KEY}"
update_env SENTRY_EVENT_RETENTION_DAYS 90
update_env SENTRY_BIND              "127.0.0.1:9000"
update_env SENTRY_IMAGE             "getsentry/sentry:${SENTRY_VERSION}"
update_env SNUBA_IMAGE              "getsentry/snuba:${SENTRY_VERSION}"
update_env RELAY_IMAGE              "getsentry/relay:${SENTRY_VERSION}"
update_env SYMBOLICATOR_IMAGE       "getsentry/symbolicator:${SENTRY_VERSION}"

echo "==> Writing sentry.conf.py overrides"
mkdir -p /opt/self-hosted/sentry
cat > /opt/self-hosted/sentry/sentry.conf.py.overrides <<PYCONF
SENTRY_OPTIONS["system.url-prefix"] = "https://${SENTRY_DOMAIN}"
SENTRY_OPTIONS["mail.host"]    = "${SMTP_HOST}"
SENTRY_OPTIONS["mail.port"]    = ${SMTP_PORT}
SENTRY_OPTIONS["mail.username"] = "${SMTP_USER}"
SENTRY_OPTIONS["mail.password"] = "${SMTP_PASS}"
SENTRY_OPTIONS["mail.use-tls"] = True
SENTRY_OPTIONS["mail.from"]    = "${SMTP_FROM}"
PYCONF

if [[ -f /opt/self-hosted/sentry/sentry.conf.py ]] && ! grep -q 'system.url-prefix' /opt/self-hosted/sentry/sentry.conf.py; then
  echo "" >> /opt/self-hosted/sentry/sentry.conf.py
  cat /opt/self-hosted/sentry/sentry.conf.py.overrides >> /opt/self-hosted/sentry/sentry.conf.py
fi

cat > /opt/self-hosted/sentry/config.yml.overrides <<YML
system.url-prefix: 'https://${SENTRY_DOMAIN}'
mail.backend: 'smtp'
mail.host: '${SMTP_HOST}'
mail.port: ${SMTP_PORT}
mail.username: '${SMTP_USER}'
mail.password: '${SMTP_PASS}'
mail.use-tls: true
mail.from: '${SMTP_FROM}'
YML
if [[ -f /opt/self-hosted/sentry/config.yml ]] && ! grep -q 'system.url-prefix' /opt/self-hosted/sentry/config.yml; then
  echo "" >> /opt/self-hosted/sentry/config.yml
  cat /opt/self-hosted/sentry/config.yml.overrides >> /opt/self-hosted/sentry/config.yml
fi

echo "==> Running install.sh (non-interactive, this takes 10-25 minutes)"
cd /opt/self-hosted
./install.sh --no-user-prompt --skip-commit-check

echo "==> Starting the stack"
docker compose up -d

echo "==> Waiting for /_health/ to return healthy"
for i in {1..120}; do
  if curl -fsS http://127.0.0.1:9000/_health/ 2>/dev/null | grep -q 'healthy'; then
    echo "  sentry web healthy"
    break
  fi
  sleep 5
done

echo "==> Creating initial superuser"
docker compose run --rm web createuser \
  --email "${SENTRY_ADMIN_EMAIL}" \
  --superuser \
  --no-password \
  --force-update || true

echo "==> nginx + Let's Encrypt"
apt-get -y install certbot python3-certbot-nginx

cat > /etc/nginx/sites-available/sentry <<NGINX_BOOT
server {
    listen 80;
    server_name ${SENTRY_DOMAIN};
    location /.well-known/acme-challenge/ { root /var/www/html; }
    location / { return 200 'bootstrap'; }
}
NGINX_BOOT
ln -sf /etc/nginx/sites-available/sentry /etc/nginx/sites-enabled/sentry
rm -f /etc/nginx/sites-enabled/default
mkdir -p /var/www/html
nginx -t && systemctl reload nginx

if [[ ! -d /etc/letsencrypt/live/${SENTRY_DOMAIN} ]]; then
  certbot certonly --webroot -w /var/www/html \
    -d "${SENTRY_DOMAIN}" -m "${SENTRY_EMAIL}" --agree-tos --non-interactive
fi

cat > /etc/nginx/sites-available/sentry <<NGINX
server {
    listen 80;
    server_name ${SENTRY_DOMAIN};
    location /.well-known/acme-challenge/ { root /var/www/html; }
    location / { return 301 https://\$host\$request_uri; }
}

server {
    listen 443 ssl http2;
    server_name ${SENTRY_DOMAIN};

    ssl_certificate /etc/letsencrypt/live/${SENTRY_DOMAIN}/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/${SENTRY_DOMAIN}/privkey.pem;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers HIGH:!aNULL:!MD5;
    add_header Strict-Transport-Security "max-age=31536000" always;

    client_max_body_size 100M;
    keepalive_timeout 5;

    location / {
        proxy_pass http://127.0.0.1:9000/;
        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 https;
        proxy_read_timeout 300s;
        proxy_send_timeout 300s;
    }
}
NGINX

nginx -t && systemctl reload nginx
systemctl enable --now certbot.timer 2>/dev/null || true

echo "==> Final apt upgrade"
apt-get -y upgrade

echo
echo "========================================"
echo "DONE"
echo "========================================"
echo
echo "Listeners:"
ss -lntp | grep -E ':(9000|443|80)\b' || true
echo
echo "Containers:"
docker compose -f /opt/self-hosted/docker-compose.yml ps
echo
echo "Sentry health:"
curl -s http://127.0.0.1:9000/_health/ || true
echo
echo "Public URL: https://${SENTRY_DOMAIN}/"
echo
echo "Next steps:"
echo "  1) Use the SMTP password-reset flow to set the password for ${SENTRY_ADMIN_EMAIL}"
echo "  2) Create an organization + first project in the UI"
echo "  3) Save the DSN somewhere you'll find it later"
echo "  4) Plan upgrades version-by-version: \`cd /opt/self-hosted && git checkout <next-tag> && ./install.sh\`"

Rendez-le exécutable et lancez-le :

chmod 700 /root/setup-sentry-ubuntu2204.sh
SENTRY_DOMAIN=sentry.example.com SENTRY_EMAIL=ops@example.com \
  SENTRY_ADMIN_EMAIL=admin@example.com \
  SMTP_HOST=smtp.example.com SMTP_PORT=587 \
  SMTP_USER=sentry@example.com SMTP_PASS='secret' \
  SMTP_FROM=sentry@example.com \
  /root/setup-sentry-ubuntu2204.sh

Le script affiche à la fin l’état des écouteurs, le résumé docker compose ps, le JSON de santé et l’URL publique. L’utilisateur admin est créé sans mot de passe — demandez une réinitialisation depuis la page de connexion ; le courriel passe par le câblage SMTP que le script vient de configurer, ce qui sert aussi de test de fumée pour les alertes d’issue plus tard. SENTRY_EVENT_RETENTION_DAYS=90 contrôle la rétention de partition ClickHouse ; augmentez-la délibérément, parce que le volume effectif de chaque projet croît linéairement avec ce paramètre. Les mises à jour se font version par version via install.sh ; ne sautez jamais un tag.

L’équipe Surveillance et support de Stack Harbor opère Sentry auto-hébergé avec rétention dimensionnée, cadence de mise à jour et routage d’alertes intégré au pipeline d’astreinte — réservez une revue de pile.