Aller au contenu

Déployer une pile Prometheus + Grafana sur AlmaLinux 9 (prête pour la production)

Monter une pile Prometheus 2.x + Grafana 10.x + node_exporter + alertmanager durcie sur AlmaLinux 9 — écoute localhost, nginx + TLS, rétention dimensionnée.

Vous avez installé Prometheus à partir de l’archive, déposé node_exporter sur quelques hôtes, démarré Grafana, les tableaux de bord par défaut se sont affichés, et vous avez remis ça à l’équipe. Six mois plus tard, la TSDB est coincée à 95 % d’espace disque parce que la rétention n’a jamais été dimensionnée, alertmanager est joignable sur 0.0.0.0:9093 depuis l’Internet public, deux cibles de scrape sont tombées depuis onze semaines sans que personne ne s’en aperçoive, et l’équipe a discrètement cessé de faire confiance aux tableaux de bord.

Ce qui se passe

Une pile Prometheus + Grafana qui tient en production demande plus que le déballage du binaire. Chaque démon — prometheus, alertmanager, node_exporter — doit tourner sous son propre utilisateur système avec une vraie unité systemd, pas dans un screen. Les écouteurs du plan de données (9090, 9093, 9100) doivent être sur 127.0.0.1 parce que la seule chose qui devrait les atteindre depuis l’extérieur, c’est nginx avec un certificat TLS et une porte d’authentification. La rétention doit être dimensionnée en octets et en temps, pas laissée à la valeur par défaut de 15 jours qui remplit silencieusement le disque. Les tâches de scrape ont besoin d’un squelette relabel_configs pour que l’ajout d’une cible plus tard ne demande pas d’éditer quinze lignes. Alertmanager a besoin d’au moins une route vers un canal réel — alerter en silence est pire que ne pas alerter. Aucune de ces étapes n’est individuellement difficile ; elles se composent dès que vous en sautez une.

Comment vérifier

Après installation, les écouteurs doivent être liés uniquement au localhost (le côté public, c’est nginx) :

ss -lntp | grep -E ':(9090|9093|9100|3000)\b'
# 127.0.0.1:9090   prometheus
# 127.0.0.1:9093   alertmanager
# 127.0.0.1:9100   node_exporter
# 127.0.0.1:3000   grafana

Prometheus doit rapporter toutes ses cibles en santé via sa propre API :

curl -s http://127.0.0.1:9090/api/v1/targets \
  | python3 -c 'import json,sys; d=json.load(sys.stdin); print([t["health"] for t in d["data"]["activeTargets"]])'

Le ping build info confirme que Grafana a passé son démarrage :

curl -s http://127.0.0.1:3000/api/health
# {"database":"ok","version":"10.x.x"}

Si un écouteur affiche 0.0.0.0, le périmètre est ouvert. Si le tableau de cibles est vide, la configuration de scrape n’a jamais été rechargée.

Le correctif

Enregistrez le script ci-dessous sous /root/setup-prometheus-grafana-almalinux9.sh, puis exécutez-le. Il déroule l’installation complète sur une VM AlmaLinux 9.x fraîche : mise à jour de base + EPEL, SELinux enforcing, fail2ban, mises à jour de sécurité automatiques, utilisateurs système dédiés pour chaque démon, les quatre binaires épinglés sur les lignes 2.x / 10.x courantes, un squelette de scrape localhost avec un job node et un placeholder kubernetes_sd_configs commenté, alertmanager routé vers un webhook stub, le provisioning Grafana qui pointe sur le Prometheus local par défaut, nginx + certbot pour l’interface externe, la rétention dimensionnée à la fois en --storage.tsdb.retention.time et en --storage.tsdb.retention.size, et LimitNOFILE=64000 sur chaque unité. Le script attend chaque écouteur avant de continuer.

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

### AlmaLinux 9.x Prometheus + Grafana clean VM installer
### Pins Prometheus 2.x, Alertmanager 0.27.x, node_exporter 1.8.x, Grafana 10.x
### All daemons bind to 127.0.0.1; only nginx is public
### TLS via Let's Encrypt; retention sized at 30d / 40GB by default
### Keeps root SSH key login; disables password auth
### No local backups; assumes VM-level backup

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

: "${OBS_DOMAIN:?Set OBS_DOMAIN, e.g. metrics.example.com}"
: "${OBS_EMAIL:?Set OBS_EMAIL for Let's Encrypt}"

PROM_VERSION="2.54.1"
ALERTMGR_VERSION="0.27.0"
NODE_EXP_VERSION="1.8.2"
GRAFANA_VERSION="10.4.5"

echo
echo "========================================"
echo "Prometheus + Grafana AlmaLinux 9 Setup"
echo "Domain: $OBS_DOMAIN"
echo "========================================"
echo

echo "==> Updating base OS"
dnf -y update
dnf -y install epel-release
dnf -y update

echo "==> Installing base packages"
dnf -y install \
  curl wget tar gzip unzip vim ca-certificates \
  chrony fail2ban dnf-automatic \
  policycoreutils-python-utils \
  lsof tcpdump bind-utils iproute net-tools \
  nginx

systemctl enable --now chronyd
timedatectl set-ntp true

echo "==> SELinux enforcing on next boot"
sed -i 's/^SELINUX=.*/SELINUX=enforcing/' /etc/selinux/config || true
setenforce 1 2>/dev/null || true

echo "==> sysctl + file limits"
cat > /etc/sysctl.d/99-observability.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
kernel.dmesg_restrict = 1
SYSCTL
sysctl --system

cat > /etc/security/limits.d/99-observability.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 sshd

echo "==> fail2ban + dnf-automatic"
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/dnf/automatic.conf <<'DNFA'
[commands]
upgrade_type = security
random_sleep = 900
download_updates = yes
apply_updates = yes
[emitters]
emit_via = stdio
[base]
debuglevel = 1
DNFA
systemctl enable --now dnf-automatic.timer

echo "==> Creating system users"
for u in prometheus alertmanager node_exporter; do
  id -u "$u" >/dev/null 2>&1 || useradd -rs /sbin/nologin "$u"
done

echo "==> Installing Prometheus ${PROM_VERSION}"
cd /tmp
curl -fsSLO "https://github.com/prometheus/prometheus/releases/download/v${PROM_VERSION}/prometheus-${PROM_VERSION}.linux-amd64.tar.gz"
tar xf "prometheus-${PROM_VERSION}.linux-amd64.tar.gz"
install -m 0755 "prometheus-${PROM_VERSION}.linux-amd64/prometheus" /usr/local/bin/prometheus
install -m 0755 "prometheus-${PROM_VERSION}.linux-amd64/promtool" /usr/local/bin/promtool
mkdir -p /etc/prometheus /var/lib/prometheus
chown -R prometheus:prometheus /etc/prometheus /var/lib/prometheus

echo "==> Writing prometheus.yml (localhost scrape skeleton)"
cat > /etc/prometheus/prometheus.yml <<'PROMYML'
global:
  scrape_interval: 30s
  evaluation_interval: 30s
  external_labels:
    cluster: 'default'

alerting:
  alertmanagers:
    - static_configs:
        - targets:
            - 127.0.0.1:9093

rule_files:
  - /etc/prometheus/rules/*.yml

scrape_configs:
  - job_name: 'prometheus'
    static_configs:
      - targets: ['127.0.0.1:9090']

  - job_name: 'node'
    static_configs:
      - targets:
          - 127.0.0.1:9100
        labels:
          host: 'observability'
    relabel_configs:
      - source_labels: [__address__]
        regex: '([^:]+):.*'
        target_label: instance
        replacement: '$1'

  # Uncomment to add more nodes:
  # - job_name: 'fleet'
  #   static_configs:
  #     - targets:
  #         - app01.internal:9100
  #         - app02.internal:9100
PROMYML

mkdir -p /etc/prometheus/rules
cat > /etc/prometheus/rules/node.yml <<'RULES'
groups:
  - name: node-basic
    interval: 1m
    rules:
      - alert: NodeDown
        expr: up{job="node"} == 0
        for: 5m
        labels:
          severity: warning
        annotations:
          summary: 'node_exporter down on {{ $labels.instance }}'
      - alert: NodeDiskFillingUp
        expr: (node_filesystem_avail_bytes{mountpoint="/"} / node_filesystem_size_bytes{mountpoint="/"}) < 0.1
        for: 30m
        labels:
          severity: warning
        annotations:
          summary: 'Root disk < 10% on {{ $labels.instance }}'
RULES
chown -R prometheus:prometheus /etc/prometheus

# Retention sizing note:
# Roughly 1-2 bytes per sample on disk after compaction.
# A node with ~200 metrics scraped every 30s produces ~1 GB/day.
# 30d retention => allow ~40 GB; bump --storage.tsdb.retention.size accordingly.

cat > /etc/systemd/system/prometheus.service <<'PROMUNIT'
[Unit]
Description=Prometheus
After=network-online.target
Wants=network-online.target

[Service]
User=prometheus
Group=prometheus
Type=simple
LimitNOFILE=64000
ExecStart=/usr/local/bin/prometheus \
  --config.file=/etc/prometheus/prometheus.yml \
  --storage.tsdb.path=/var/lib/prometheus \
  --storage.tsdb.retention.time=30d \
  --storage.tsdb.retention.size=40GB \
  --web.listen-address=127.0.0.1:9090 \
  --web.external-url=https://OBS_DOMAIN_PLACEHOLDER/prometheus \
  --web.route-prefix=/prometheus
Restart=on-failure
RestartSec=5s

[Install]
WantedBy=multi-user.target
PROMUNIT
sed -i "s|OBS_DOMAIN_PLACEHOLDER|${OBS_DOMAIN}|" /etc/systemd/system/prometheus.service

echo "==> Installing Alertmanager ${ALERTMGR_VERSION}"
curl -fsSLO "https://github.com/prometheus/alertmanager/releases/download/v${ALERTMGR_VERSION}/alertmanager-${ALERTMGR_VERSION}.linux-amd64.tar.gz"
tar xf "alertmanager-${ALERTMGR_VERSION}.linux-amd64.tar.gz"
install -m 0755 "alertmanager-${ALERTMGR_VERSION}.linux-amd64/alertmanager" /usr/local/bin/alertmanager
install -m 0755 "alertmanager-${ALERTMGR_VERSION}.linux-amd64/amtool" /usr/local/bin/amtool
mkdir -p /etc/alertmanager /var/lib/alertmanager
chown -R alertmanager:alertmanager /etc/alertmanager /var/lib/alertmanager

cat > /etc/alertmanager/alertmanager.yml <<'AMYML'
global:
  resolve_timeout: 5m

route:
  receiver: 'default'
  group_by: ['alertname', 'cluster']
  group_wait: 30s
  group_interval: 5m
  repeat_interval: 4h

receivers:
  - name: 'default'
    webhook_configs:
      - url: 'http://127.0.0.1:5001/'
        send_resolved: true
AMYML
chown -R alertmanager:alertmanager /etc/alertmanager

cat > /etc/systemd/system/alertmanager.service <<'AMUNIT'
[Unit]
Description=Alertmanager
After=network-online.target
Wants=network-online.target

[Service]
User=alertmanager
Group=alertmanager
Type=simple
LimitNOFILE=64000
ExecStart=/usr/local/bin/alertmanager \
  --config.file=/etc/alertmanager/alertmanager.yml \
  --storage.path=/var/lib/alertmanager \
  --web.listen-address=127.0.0.1:9093
Restart=on-failure
RestartSec=5s

[Install]
WantedBy=multi-user.target
AMUNIT

echo "==> Installing node_exporter ${NODE_EXP_VERSION}"
curl -fsSLO "https://github.com/prometheus/node_exporter/releases/download/v${NODE_EXP_VERSION}/node_exporter-${NODE_EXP_VERSION}.linux-amd64.tar.gz"
tar xf "node_exporter-${NODE_EXP_VERSION}.linux-amd64.tar.gz"
install -m 0755 "node_exporter-${NODE_EXP_VERSION}.linux-amd64/node_exporter" /usr/local/bin/node_exporter

cat > /etc/systemd/system/node_exporter.service <<'NEUNIT'
[Unit]
Description=node_exporter
After=network-online.target
Wants=network-online.target

[Service]
User=node_exporter
Group=node_exporter
Type=simple
LimitNOFILE=64000
ExecStart=/usr/local/bin/node_exporter \
  --web.listen-address=127.0.0.1:9100
Restart=on-failure
RestartSec=5s

[Install]
WantedBy=multi-user.target
NEUNIT

echo "==> Installing Grafana ${GRAFANA_VERSION}"
cat > /etc/yum.repos.d/grafana.repo <<'GREPO'
[grafana]
name=grafana
baseurl=https://rpm.grafana.com
repo_gpgcheck=1
enabled=1
gpgcheck=1
gpgkey=https://rpm.grafana.com/gpg.key
sslverify=1
sslcacert=/etc/pki/tls/certs/ca-bundle.crt
GREPO
dnf -y install "grafana-${GRAFANA_VERSION}"

sed -i 's|^;http_addr =.*|http_addr = 127.0.0.1|' /etc/grafana/grafana.ini
sed -i 's|^;root_url =.*|root_url = https://OBS_DOMAIN_PLACEHOLDER/grafana/|' /etc/grafana/grafana.ini
sed -i 's|^;serve_from_sub_path =.*|serve_from_sub_path = true|' /etc/grafana/grafana.ini
sed -i "s|OBS_DOMAIN_PLACEHOLDER|${OBS_DOMAIN}|" /etc/grafana/grafana.ini

mkdir -p /etc/grafana/provisioning/datasources
cat > /etc/grafana/provisioning/datasources/prometheus.yml <<'DSYML'
apiVersion: 1
datasources:
  - name: Prometheus
    type: prometheus
    access: proxy
    url: http://127.0.0.1:9090/prometheus
    isDefault: true
    editable: false
DSYML

mkdir -p /etc/systemd/system/grafana-server.service.d
cat > /etc/systemd/system/grafana-server.service.d/limits.conf <<'GLIM'
[Service]
LimitNOFILE=64000
GLIM

systemctl daemon-reload

echo "==> Starting prometheus, alertmanager, node_exporter, grafana"
systemctl enable --now node_exporter
systemctl enable --now alertmanager
systemctl enable --now prometheus
systemctl enable --now grafana-server

echo "==> Waiting for all listeners on 127.0.0.1"
for port in 9100 9093 9090 3000; do
  for i in {1..30}; do
    if ss -lntp | grep -q "127.0.0.1:${port}"; then
      echo "  ${port} up"
      break
    fi
    sleep 1
  done
done

echo "==> Configuring nginx reverse proxy"
cat > /etc/nginx/conf.d/observability.conf <<NGINX
server {
    listen 80;
    server_name ${OBS_DOMAIN};
    location /.well-known/acme-challenge/ { root /var/lib/letsencrypt; }
    location / { return 301 https://\$host\$request_uri; }
}

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

    ssl_certificate /etc/letsencrypt/live/${OBS_DOMAIN}/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/${OBS_DOMAIN}/privkey.pem;

    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers HIGH:!aNULL:!MD5;
    add_header Strict-Transport-Security "max-age=31536000" always;

    location /grafana/ {
        proxy_pass http://127.0.0.1:3000/;
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-Proto https;
    }

    location /prometheus/ {
        proxy_pass http://127.0.0.1:9090/prometheus/;
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
    }
}
NGINX

mkdir -p /var/lib/letsencrypt
dnf -y install certbot python3-certbot-nginx
systemctl enable --now nginx

if [[ ! -d /etc/letsencrypt/live/${OBS_DOMAIN} ]]; then
  cat > /etc/nginx/conf.d/observability.conf <<NGINX_BOOT
server {
    listen 80;
    server_name ${OBS_DOMAIN};
    location /.well-known/acme-challenge/ { root /var/lib/letsencrypt; }
    location / { return 200 'bootstrap'; }
}
NGINX_BOOT
  nginx -t && systemctl reload nginx
  certbot certonly --webroot -w /var/lib/letsencrypt \
    -d "${OBS_DOMAIN}" -m "${OBS_EMAIL}" --agree-tos --non-interactive
fi

cat > /etc/nginx/conf.d/observability.conf <<NGINX
server {
    listen 80;
    server_name ${OBS_DOMAIN};
    location /.well-known/acme-challenge/ { root /var/lib/letsencrypt; }
    location / { return 301 https://\$host\$request_uri; }
}

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

    ssl_certificate /etc/letsencrypt/live/${OBS_DOMAIN}/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/${OBS_DOMAIN}/privkey.pem;

    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers HIGH:!aNULL:!MD5;
    add_header Strict-Transport-Security "max-age=31536000" always;

    location /grafana/ {
        proxy_pass http://127.0.0.1:3000/;
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-Proto https;
    }

    location /prometheus/ {
        proxy_pass http://127.0.0.1:9090/prometheus/;
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
    }
}
NGINX

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

echo "==> Final package update"
dnf -y update

echo
echo "========================================"
echo "DONE"
echo "========================================"
echo
echo "Listeners:"
ss -lntp | grep -E ':(9090|9093|9100|3000|443|80)\b' || true
echo
echo "Services:"
systemctl is-active prometheus alertmanager node_exporter grafana-server nginx fail2ban chronyd || true
echo
echo "Prometheus target health:"
curl -s http://127.0.0.1:9090/api/v1/targets | head -c 500 || true
echo
echo "Grafana URL:    https://${OBS_DOMAIN}/grafana/  (admin / admin — change on first login)"
echo "Prometheus URL: https://${OBS_DOMAIN}/prometheus/"
echo
echo "Final step: reboot to confirm SELinux + units come up clean."

Rendez-le exécutable et lancez-le :

chmod 700 /root/setup-prometheus-grafana-almalinux9.sh
OBS_DOMAIN=metrics.example.com OBS_EMAIL=ops@example.com /root/setup-prometheus-grafana-almalinux9.sh

Le script affiche à la fin le résumé des écouteurs, l’état de santé des cibles et les URL publiques. Après la première connexion à Grafana, faites tourner le mot de passe admin et importez les tableaux de bord 1860 (node_exporter complet) et 3662 (vue d’ensemble Prometheus 2.0) comme point de départ. La rétention est dimensionnée à 30 jours / 40 Go par défaut — ajustez les deux drapeaux ensemble si vous ajoutez des cibles de scrape, parce que la taille est la borne qui mord en premier sur un nœud chargé.

L’équipe Surveillance et support de Stack Harbor exploite des piles Prometheus comme celle-ci avec patching, revue de rétention et escalade Sev-1 dans le cadre des environnements infogérés — réservez une revue de pile.