System & Network Prometheus + Grafana
Bài 15 · Giai đoạn 2 — Hạ tầng nền tảng

Monitor Stack Prometheus + Grafana

Xây dựng hệ thống giám sát và cảnh báo toàn diện cho hạ tầng.

VM235 Ubuntu 24.04 Giai đoạn: Hạ tầng nền tảng

Bối cảnh & Lý do triển khai

Vị trí trong chuỗi bài: Bài 15 thuộc Giai đoạn 2 — Hạ tầng nền tảng, nối tiếp Bài 14. Authentik SSO và đứng trước Bài 16. Mailu Mail Server. Cần có sẵn / liên quan: 04. Triển khai PBS + PDM · 12. Pi-hole DNS · 13. step-CA PKI · 14. Authentik SSO.
Mức độ cần thiết: 🔴 Bắt buộc — Observability, không có monitoring là "bay mù"

Hạ tầng không có monitoring giống như lái xe không có đồng hồ. Khi disk đầy, RAM cạn, hay service down — chỉ biết khi user phản ánh, lúc đó thiệt hại đã xảy ra. Stack này cung cấp visibility toàn diện: metrics, uptime, và push notification tức thì đến điện thoại.

MụcNội dung
Ứng dụng trong DNOperations dashboard cho IT team, on-call alerting, capacity planning, SLA tracking, trend analysis
Tác dụng chínhMetrics từ 4 node PVE + 30 VM (+ ops01) qua node_exporter; metrics cụm Proxmox và UPS qua pve-exporter/nut_exporter (Bước 11); Grafana dashboard; Alertmanager gửi email cảnh báo qua Mailu (bài 16); Uptime Kuma monitor HTTP; Gotify push alert
Nếu không triển khaiSự cố chỉ biết sau khi xảy ra, không có dữ liệu để phân tích nguyên nhân gốc rễ
Các service phụ thuộc vào đâyTất cả VM cài node_exporter; Wazuh, Pi-hole, Mailu push metrics về Prometheus

Phiên bản: 1.1 | Ngày cập nhật: 2026-10-15 (nâng lên Ubuntu Server 24.04 LTS, node_exporter 1.12.1; thêm Bước 11)
Cluster: HOATRANHUB (PVE 9.2.20) | Tác giả: HoatranLabs

Danh sách máy chủ & IP liên quan

Bảng dưới liệt kê các máy chủ mà bài này tạo hoặc kết nối tới. Địa chỉ, VMID, VLAN và node lấy từ bảng quy hoạch chung của lab, dùng thống nhất cho cả bộ bài lab.

Máy chủIPVLAN · NodeVai trò trong bài này
prometheus (Prometheus + Alertmanager) · VM23510.11.45.3545 (MGMT) · node2Máy chủ của bài — chạy Prometheus :9090, Alertmanager :9093 và node_exporter bằng Docker Compose; scrape mỗi 15 giây, lưu 15 ngày (tối đa 8 GB).
grafana (Grafana + Uptime Kuma + Gotify) · VM23610.11.45.3645 (MGMT) · node2Máy chủ của bài — chạy Grafana :3000, Uptime Kuma :3001, Gotify :3002 và node_exporter bằng Docker Compose; lấy dữ liệu từ Prometheus.
node2 (Proxmox VE)10.11.45.21145 (MGMT) · cluster HOATRANHUBNode Proxmox chứa VM235 và VM236; tạo VM, lịch backup (daily 03:30) tại đây; node1–node4 được scrape :9100 và gọi API :8006 (Bước 11).
ops01 (Ansible/OpenTofu + bastion) · VM29010.11.45.2045 (MGMT) · node2Máy quản trị/tự động hoá (bài 07, Ubuntu 24.04): cài node_exporter 1.12.1 bằng script Bước 5 và là target :9100 trong job vlan-mgmt-vms.
ups01 (UPS có SNMP/NMC + NUT)10.11.45.1945 (MGMT) · thiết bịUPS (bài 10): NUT trên node1 đọc UPS; nut_exporter trên VM235 lấy số liệu qua NUT :3493 (job nut, Bước 11).
FortiGate (firewall)10.100.100.1Quản trị 10.100.100.0/24 · thiết bị mạngTạo rule: Prometheus scrape :9100 tới mọi VM, Grafana tới Prometheus :9090, Alertmanager và Grafana tới Mailu :587, web UI :3000-3002.
pihole (Pi-hole DNS) · VM24710.11.45.5345 (MGMT) · node3DNS của hai VM; thêm bản ghi A prometheus, grafana, kuma, gotify (bài 12); được scrape :9100 và Uptime Kuma kiểm tra HTTP /admin.
authentik (Authentik SSO) · VM23410.11.25.4025 (SEC) · node1Nhà cung cấp OIDC (:9443) cho đăng nhập SSO của Grafana (bài 14); Uptime Kuma kiểm tra health check HTTP cổng 9000.
pbs01 (PBS Primary) · VM10110.11.45.1745 (MGMT) · node4Đích backup (storage pbs-primary) của VM235 và VM236: snapshot daily 03:30, retention do Prune Job trên PBS quản lý; cũng là target scrape :9100.
step-ca (step-CA PKI) · VM24210.11.25.4225 (SEC) · node1Cung cấp root CA (bài 13) cài lên hai VM, mount vào container để Prometheus, Alertmanager và Grafana tin cậy chứng chỉ nội bộ.
mailu (Mailu Mail Server) · VM24610.11.35.4635 (DMZ) · node2Relay SMTP cổng 587 (STARTTLS, có xác thực) gửi email cảnh báo của Alertmanager (alerts@) và Grafana (noreply@) (bài 16).
K3s cluster (3 control plane + 3 worker) · VM 260–26510.11.65.60–6565 (SRV) · node1–node3Cụm K3s đẩy remote_write về Prometheus :9090 (bài 28) và các node được scrape node_exporter :9100.

Gateway của mỗi VLAN là địa chỉ .1. Tên DNS nội bộ do Pi-hole phân giải (bài 12). Tên in đậm là hostname; FQDN = hostname + .hoatranlabs.local. Prometheus scrape node_exporter :9100 trên 4 node PVE và hầu hết VM Linux của lab (danh sách đầy đủ ở Bước 2), nên bảng chỉ kê các máy có cấu hình riêng trong bài.

Phụ thuộc (Dependencies)

Trước khi thực hiện file này, đảm bảo các thành phần sau đã hoạt động:

Thành phầnVMIDIPTrạng thái cần có
PVE Cluster (node1–node4)—10.11.45.210–213Running
FortiGate (gateway VLAN_MGMT)—10.11.45.1Running
Pi-hole DNSVM24710.11.45.53Running
Authentik SSOVM23410.11.25.40Running (cho OIDC)
PBS Backup (pbs01)VM10110.11.45.17Running
Ceph storage pool vm-ceph——Healthy
step-CA (root CA, bài 13)VM24210.11.25.42Running (root CA được cài lên VM235/VM236 để Prometheus, Alertmanager, Grafana tin cậy chứng chỉ nội bộ)
Mailu (bài 16) được triển khai sau bài này. Alertmanager (Bước 2) và Grafana (Bước 4) đã khai báo sẵn SMTP tới mailu.hoatranlabs.local:587; email thử chỉ gửi thành công sau khi Mailu chạy và đã tạo mailbox alerts@ và [email protected] (bài 16, mục 6).
Tích hợp với các bài vận hành Proxmox (bài 05–11, chỉ ở mức tham chiếu): ops01 (VM290, 10.11.45.20, tạo ở bài 07) được scrape node_exporter như một VM Linux; Bước 11 dùng token API svc-monitoring@pve!prometheus (tạo ở bài 08) cho pve-exporter và máy chủ NUT trên node1 (bài 10) cho nut_exporter. Nếu chưa làm bài 08/10, bỏ qua Bước 11, phần lõi của bài vẫn chạy độc lập.

Tổng Quan Kiến Trúc

Phiên bản phần mềm sử dụng

Phiên bản phần mềm sử dụng

Đã xác minh 2026-10-15 (số phiên bản ứng dụng giữ như bản cũ của bài, chỉ node_exporter dùng giá trị chung của series):

Thành phầnPhiên bảnGhi chú
Hệ điều hành VM235/VM236Ubuntu Server 24.04 LTS "Noble Numbat" (ISO ubuntu-24.04.5-live-server-amd64.iso)Kernel 6.8, systemd 255, netplan 1.0, APT 2.7 (nguồn deb822), hỗ trợ chuẩn tới 04/2029. Bản point mới nhất thấy trên releases.ubuntu.com/24.04 là 24.04.5 (cần kiểm lại khi tải ISO).
Docker Engine + plugin Compose29.9.1 (docker-ce, đăng lên repo ngày 2026-10-14) + plugin Compose 5.6.0, từ repo download.docker.com/linux/ubuntu noble stableGói docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin; lệnh docker compose. Số bản đọc từ thư mục dists/noble/pool/stable/amd64/ của repo ngày 2026-10-15 (containerd.io 2.4.2-2, buildx 0.38.0-1); apt sẽ lấy bản mới nhất trong repo lúc cài nên có thể cao hơn. Docker rootful nên không bị giới hạn user namespace của AppArmor 4 (Ubuntu 24.04).
node_exporter1.12.1 (2026-07-14)Dùng cho script Bước 5 (binary, kèm SHA-256) và image prom/node-exporter:v1.12.1 của VM235/VM236; giá trị chung của series bài. Trước đây bài ghim 1.8.2.
Prometheus, Alertmanager, Grafana, Uptime Kuma, Gotifyimage :latest như bản cũ của bàiChưa ghim phiên bản; nên ghim tag cụ thể (xem tag trên Docker Hub) trước khi đưa vào production.
prometheus-pve-exporter3.10.1 (2026-10-03), image prompve/prometheus-pve-exporter:3.10.1Chỉ dùng ở Bước 11 (tuỳ chọn). Yêu cầu Python >= 3.11 nếu cài bằng pip; Ubuntu 24.04 có Python 3.12 nhưng pip ngoài venv bị chặn (PEP 668), nên bài dùng container.
nut_exporter (DRuggeri)3.3.0, image druggeri/nut_exporter:3.3.0Chỉ dùng ở Bước 11 (tuỳ chọn); cổng mặc định 9199.

Sơ đồ:

┌─────────────────────────────┐
                │  VM235: prometheus           │
                │  10.11.45.35 | VLAN_MGMT    │
                │  Prometheus :9090            │
                │  Alertmanager :9093          │
                │  node_exporter :9100         │
                └────────────┬────────────────┘
                             │ scrape metrics
          ┌──────────────────▼────────────────────────┐
          │  30 VMs + 4 PVE nodes (node_exporter :9100)│
          └──────────────────┬────────────────────────┘
                             │ datasource HTTP
                ┌────────────▼────────────────┐
                │  VM236: grafana              │
                │  10.11.45.36 | VLAN_MGMT    │
                │  Grafana     :3000           │
                │  Uptime Kuma :3001           │
                │  Gotify      :3002           │
                │  node_exporter :9100         │
                └─────────────────────────────┘

Luồng dữ liệu:

  • Prometheus (VM235) pull metrics từ tất cả VM mỗi 15 giây, lưu time-series 15 ngày (tối đa 8 GB, xem Bước 2); cũng nhận remote_write từ K3s (bài 28).
  • Prometheus (VM235) đẩy alert sang Alertmanager (container alertmanager, cùng VM235, cổng 9093); Alertmanager gửi email qua Mailu (bài 16).
  • Grafana (VM236) kết nối Prometheus làm datasource, hiển thị dashboard.
  • Uptime Kuma (VM236) kiểm tra HTTP/TCP uptime cho mọi service, gửi alert qua Gotify.
  • Gotify (VM236) nhận push notification từ Uptime Kuma và Grafana alert.
01

Tạo VM235 (Prometheus)

Chạy lệnh sau trên node PVE bất kỳ (khuyến nghị node2):

Cách 1: Web UI Proxmox (GUI)

1
Đăng nhập Proxmox Web UI → chọn Node: node2 → nhấn Create VM (góc trên phải)
2
General:
  • VM ID: 235
  • Name: prometheus
  • Bỏ tick Start after created
3
OS:
  • Storage: local (hoặc nơi chứa ISO)
  • ISO Image: ubuntu-24.04.5-live-server-amd64.iso
  • Guest OS Type: Linux, Version: 6.x - 2.6 Kernel
4
System:
  • Machine: q35
  • SCSI Controller: VirtIO SCSI single
  • BIOS: SeaBIOS
  • Qemu Agent: ☑
5
Disks:
  • Bus/Device: SCSI 0, Storage: vm-ceph (thường là vm-ceph)
  • Disk size: 40 GiB (đúng cột disk của bài 07; đĩa dữ liệu Loki scsi1 thêm ở bài 33), Cache: Write back, Discard: ☑
6
CPU:
  • Sockets: 1, Cores: 4, Type: x86-64-v2-AES
7
Memory:
  • Memory (MiB): 4096
8
Network:
  • Bridge: vmbr0, VLAN Tag: 45, Model: VirtIO (paravirtualized), Firewall: ☐
9
Confirm: Xem lại → Finish → Start VM → Console để bắt đầu cài Ubuntu.
Proxmox Create VM → tab Confirm: VM 235 prometheus trên node2, 4 core, 4096 MiB, scsi0 40 GiB vm-ceph, net0 VirtIO vmbr0 tag 45.
Proxmox Create VM → tab Confirm: VM 235 prometheus trên node2, 4 core, 4096 MiB, scsi0 40 GiB vm-ceph, net0 VirtIO vmbr0 tag 45.

Cách 2: CLI (qm create)

qm create 235 \
  --name prometheus \
  --memory 4096 \
  --cores 4 \
  --net0 virtio,bridge=vmbr0,tag=45 \
  --scsi0 vm-ceph:40 \
  --scsihw virtio-scsi-pci \
  --ide2 local:iso/ubuntu-24.04.5-live-server-amd64.iso,media=cdrom \
  --boot "order=ide2;scsi0" \
  --ostype l26 \
  --agent enabled=1 \
  --onboot 1 \
  --startup order=3,up=30
Dung lượng theo bài 07 (mục 8.4–8.6): VM235 có disk 40 GB trên SSD vm-ceph (thin; hệ điều hành, Docker, image và TSDB Prometheus) và xdisk 30 GB trên HDD vm-bulk dành cho dữ liệu Loki (bài 33). Dựng VM từ template ở bài 07 thì bỏ qua mục tạo VM này, đĩa đã có sẵn.

Cài đặt OS Ubuntu Server 24.04 LTS:

Hostname    : prometheus
Username    : sysadmin
Password    : <mật khẩu mạnh>
IP          : 10.11.45.35/24
Gateway     : 10.11.45.1
DNS         : 10.11.45.53
Trên VM q35 tên NIC thường là ens18 hoặc enp6s18: kiểm bằng ip -br link trước khi viết netplan. Trình cài đặt/cloud-init của Ubuntu 24.04 có thể tự ghi /etc/netplan/50-cloud-init.yaml; sửa đúng file đó (quyền 600) rồi chạy sudo netplan try.

Sau khi cài xong, eject ISO:

qm set 235 --ide2 none

Cài Docker và chuẩn bị hệ thống (repo chính thức của Docker cho Ubuntu 24.04 "noble", nguồn dạng deb822 docker.sources, theo docs.docker.com/engine/install/ubuntu):

# Ubuntu 24.04 có needrestart: tránh hộp thoại hỏi khi apt chạy trong script
export NEEDRESTART_MODE=a DEBIAN_FRONTEND=noninteractive

apt update && apt upgrade -y
apt install -y curl wget git ca-certificates gnupg

# Gỡ gói Docker không chính thức nếu có (bỏ qua lỗi nếu chưa cài)
apt remove -y docker.io docker-compose docker-compose-v2 docker-doc podman-docker containerd runc || true

# Cài Docker từ repo chính thức
install -m 0755 -d /etc/apt/keyrings
curl -fsSL https://download.docker.com/linux/ubuntu/gpg -o /etc/apt/keyrings/docker.asc
chmod a+r /etc/apt/keyrings/docker.asc

tee /etc/apt/sources.list.d/docker.sources > /dev/null <<EOF
Types: deb
URIs: https://download.docker.com/linux/ubuntu
Suites: $(. /etc/os-release && echo "${UBUNTU_CODENAME:-$VERSION_CODENAME}")
Components: stable
Architectures: $(dpkg --print-architecture)
Signed-By: /etc/apt/keyrings/docker.asc
EOF

apt update
apt install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin

systemctl enable --now docker
docker --version && docker compose version
02

Cài Prometheus trên VM235

mkdir -p /opt/prometheus/alertmanager /opt/prometheus/rules /opt/prometheus/data
chown 65534:65534 /opt/prometheus/data    # container prom/prometheus chạy bằng user nobody (UID 65534)
cd /opt/prometheus

Cấu trúc thư mục trên VM235 (các bài sau tham chiếu đúng các đường dẫn này):

Đường dẫnNội dung
/opt/prometheus/docker-compose.ymlCompose của VM235 (container prometheus, alertmanager, node-exporter)
/opt/prometheus/prometheus.ymlCấu hình Prometheus (scrape, rule_files, alerting)
/opt/prometheus/rules/*.ymlFile rule cảnh báo (bài này chưa có rule nào; thêm vào đây rồi reload Prometheus)
/opt/prometheus/alertmanager/alertmanager.ymlCấu hình Alertmanager (container alertmanager, cổng 9093)
/opt/prometheus/dataTSDB của Prometheus (bind mount vào /prometheus), nằm trên đĩa SSD scsi0; giữ 15 ngày, tối đa 8 GB

Cài root CA của step-CA lên VM235 (bài 13, Bước 9: chạy distribute-root-ca.sh). Container Prometheus mount file này để scrape các endpoint HTTPS nội bộ (tls_config.ca_file, ví dụ Vault, SeaweedFS S3); container Alertmanager mount cùng file để kiểm tra chứng chỉ STARTTLS của Mailu và webhook HTTPS nội bộ (Mattermost). File phải tồn tại TRƯỚC khi docker compose up, nếu không Docker sẽ tự tạo một thư mục rỗng tại đường dẫn đó:

ls -l /usr/local/share/ca-certificates/hoatranlabs-root.crt

Tạo file prometheus.yml:

cat > /opt/prometheus/prometheus.yml << 'EOF'
global:
  scrape_interval: 15s
  evaluation_interval: 15s
  external_labels:
    cluster: 'hoatranlabs'
    environment: 'production'

# Rule cảnh báo: đặt các file *.yml vào /opt/prometheus/rules/ (trong container: /etc/prometheus/rules/)
rule_files:
  - /etc/prometheus/rules/*.yml

# Đẩy alert sang Alertmanager (container `alertmanager`, cùng mạng Docker `monitoring`)
alerting:
  alertmanagers:
    - static_configs:
        - targets: ['alertmanager:9093']

scrape_configs:
  # Prometheus tự monitor
  - job_name: 'prometheus'
    static_configs:
      - targets: ['10.11.45.35:9090']
        labels:
          instance: 'prometheus'

  # 4 PVE nodes
  - job_name: 'pve-nodes'
    static_configs:
      - targets:
          - '10.11.45.210:9100'
          - '10.11.45.211:9100'
          - '10.11.45.212:9100'
          - '10.11.45.213:9100'
        labels:
          job: 'pve-node-exporter'

  # VLAN_MGMT VMs (VLAN 45)
  - job_name: 'vlan-mgmt-vms'
    static_configs:
      - targets:
          - '10.11.45.35:9100'   # VM235 prometheus (container node-exporter)
          - '10.11.45.36:9100'   # VM236 grafana (container node-exporter)
          - '10.11.45.53:9100'   # VM247 pihole
          - '10.11.45.25:9100'   # VM280 wazuh-siem
          - '10.11.45.20:9100'   # VM290 ops01 (máy quản trị/tự động hoá, Ubuntu 24.04, tạo ở bài 07)
          - '10.11.45.39:9100'   # VM239 harbor
          - '10.11.45.40:9100'   # VM240 gitea
          - '10.11.45.45:9100'   # VM245 netbox
          - '10.11.45.17:9100'   # VM101 pbs01
        labels:
          vlan: 'mgmt'

  # VLAN_SEC VMs (VLAN 25)
  - job_name: 'vlan-sec-vms'
    static_configs:
      - targets:
          - '10.11.25.10:9100'   # VM269 vault
          - '10.11.25.11:9100'   # VM270 thehive
          - '10.11.25.30:9100'   # VM233 privacyidea
          - '10.11.25.40:9100'   # VM234 authentik
          - '10.11.25.42:9100'   # VM242 step-ca
          - '10.11.25.43:9100'   # VM243 vaultwarden
          - '10.11.25.44:9100'   # VM244 openvas
        labels:
          vlan: 'sec'

  # VLAN_DMZ VMs (VLAN 35)
  - job_name: 'vlan-dmz-vms'
    static_configs:
      - targets:
          - '10.11.35.10:9100'   # VM232 headscale
          - '10.11.35.20:9100'   # VM271 crowdsec
          - '10.11.35.46:9100'   # VM246 mailu
        labels:
          vlan: 'dmz'

  # VLAN_SRV VMs (VLAN 65)
  # VM250 dc1 (10.11.65.50) là Samba AD DC chạy Ubuntu 24.04 (bài 25) nên chạy node_exporter như các VM Linux khác và nằm trong danh sách này.
  - job_name: 'vlan-srv-vms'
    static_configs:
      - targets:
          - '10.11.65.41:9100'   # VM241 mediamtx
          - '10.11.65.50:9100'   # VM250 dc1 (Samba AD DC)
          - '10.11.65.51:9100'   # VM251 samba01
          - '10.11.65.57:9100'   # VM272 mattermost
          - '10.11.65.60:9100'   # VM260 k3s-cp01
          - '10.11.65.61:9100'   # VM261 k3s-cp02
          - '10.11.65.62:9100'   # VM262 k3s-cp03
          - '10.11.65.63:9100'   # VM263 k3s-worker01
          - '10.11.65.64:9100'   # VM264 k3s-worker02
          - '10.11.65.65:9100'   # VM265 k3s-worker03
          - '10.11.65.66:9100'   # VM266 sonarqube
          - '10.11.65.67:9100'   # VM267 nexus
        labels:
          vlan: 'srv'

  # VLAN_STORAGE VMs (VLAN 85)
  - job_name: 'vlan-storage-vms'
    static_configs:
      - targets:
          - '10.11.85.10:9100'   # VM268 s3 (SeaweedFS S3)
        labels:
          vlan: 'storage'

  # --- Bước 11 (tuỳ chọn, cần bài 08 và 10): metrics Proxmox VE và UPS ---
  # Chưa làm Bước 11 thì comment 3 job `pve`, `pve-per-node`, `nut` bên dưới để không có target DOWN.
  # Job `pve`: metrics cấp CỤM (guest, storage, quorum, backup...) qua prometheus-pve-exporter.
  # Mọi node trả cùng một bộ số liệu cụm nên chỉ scrape 1 node (đổi sang node2 nếu node1 tắt).
  # Dùng tên FQDN (cert của node cấp ở bài 09 khớp tên, không khớp IP).
  - job_name: 'pve'
    metrics_path: /pve
    params:
      module: [default]
      cluster: ['1']
      node: ['0']
    static_configs:
      - targets: ['node1.hoatranlabs.local']
    relabel_configs:
      - source_labels: [__address__]
        target_label: __param_target
      - source_labels: [__param_target]
        target_label: instance
      - target_label: __address__
        replacement: pve-exporter:9221   # container pve-exporter (cùng mạng Docker `monitoring`)

  # Job `pve-per-node`: metrics cấp NODE (replication, subscription, config) - phải hỏi từng node, node1..node4
  - job_name: 'pve-per-node'
    metrics_path: /pve
    params:
      module: [default]
      cluster: ['0']
      node: ['1']
    static_configs:
      - targets:
          - 'node1.hoatranlabs.local'
          - 'node2.hoatranlabs.local'
          - 'node3.hoatranlabs.local'
          - 'node4.hoatranlabs.local'
    relabel_configs:
      - source_labels: [__address__]
        target_label: __param_target
      - source_labels: [__param_target]
        target_label: instance
      - target_label: __address__
        replacement: pve-exporter:9221

  # Job `headscale`: metrics của Headscale 0.29.x (VM232, bài 20) — cổng 9090 chỉ mở cho Prometheus (10.11.45.35) trên FortiGate
  - job_name: 'headscale'
    static_configs:
      - targets: ['10.11.35.10:9090']
        labels:
          service: 'headscale'

  # Job `nut`: UPS ups01 (10.11.45.19) đọc qua máy chủ NUT trên node1 (bài 10) bằng nut_exporter
  - job_name: 'nut'
    metrics_path: /ups_metrics
    params:
      ups: ['ups01']          # đúng tên UPS khai báo trong ups.conf ở bài 10
    static_configs:
      - targets: ['nut-exporter:9199']
        labels:
          device: 'ups01'
EOF

Tạo file cấu hình Alertmanager /opt/prometheus/alertmanager/alertmanager.yml. Email cảnh báo đi qua Mailu (bài 16): mailu.hoatranlabs.local:587, STARTTLS, đăng nhập bằng mailbox [email protected], địa chỉ gửi (from) [email protected]:

cat > /opt/prometheus/alertmanager/alertmanager.yml << 'EOF'
global:
  resolve_timeout: 5m
  # SMTP relay: Mailu (bài 16), cổng 587 STARTTLS có xác thực
  smtp_smarthost: 'mailu.hoatranlabs.local:587'
  smtp_from: '[email protected]'
  smtp_auth_username: '[email protected]'
  smtp_auth_password: 'Alerts@Mailu2024!'
  smtp_require_tls: true

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

receivers:
  - name: 'default'
    email_configs:
      - to: '[email protected]'
        send_resolved: true
        tls_config:
          ca_file: /etc/prometheus/certs/hoatranlabs-root.crt
EOF
Các bài khác (16, 20, 26, 30) thêm receiver/route vào đúng file này (/opt/prometheus/alertmanager/alertmanager.yml, container alertmanager, địa chỉ alertmanager:9093 trong mạng Docker monitoring, hoặc prometheus.hoatranlabs.local:9093 từ bên ngoài). Receiver mặc định tên là default. Sau khi sửa file, nạp lại bằng docker compose restart alertmanager.

Tạo file docker-compose.yml cho VM235:

cat > /opt/prometheus/docker-compose.yml << 'EOF'
# Không khai báo `version:` (thuộc tính này đã obsolete, Docker Compose v2+ chỉ in cảnh báo)
services:
  prometheus:
    image: prom/prometheus:latest
    container_name: prometheus
    restart: unless-stopped
    ports:
      - "9090:9090"
    volumes:
      - ./prometheus.yml:/etc/prometheus/prometheus.yml:ro
      - ./rules:/etc/prometheus/rules:ro
      - ./data:/prometheus                  # TSDB tại /opt/prometheus/data (chown 65534 ở trên)
      # Root CA của step-CA (bài 13) để dùng tls_config.ca_file khi scrape HTTPS nội bộ
      - /usr/local/share/ca-certificates/hoatranlabs-root.crt:/etc/prometheus/certs/hoatranlabs-root.crt:ro
    command:
      - '--config.file=/etc/prometheus/prometheus.yml'
      - '--storage.tsdb.path=/prometheus'
      - '--storage.tsdb.retention.time=15d'     # đĩa 40 GB của bài 07; cách tính ở đoạn "Retention và dung lượng đĩa" bên dưới
      - '--storage.tsdb.retention.size=8GB'
      - '--web.enable-lifecycle'
      - '--web.enable-admin-api'
      - '--web.enable-remote-write-receiver'   # nhận remote_write từ K3s (bài 28): http://10.11.45.35:9090/api/v1/write
      - '--web.console.libraries=/etc/prometheus/console_libraries'
      - '--web.console.templates=/etc/prometheus/consoles'
    networks:
      - monitoring

  alertmanager:
    image: prom/alertmanager:latest
    container_name: alertmanager
    restart: unless-stopped
    ports:
      - "9093:9093"
    volumes:
      - ./alertmanager/alertmanager.yml:/etc/alertmanager/alertmanager.yml:ro
      - alertmanager_data:/alertmanager
      # Cùng đường dẫn root CA như container prometheus để mọi bài dùng chung một ca_file
      - /usr/local/share/ca-certificates/hoatranlabs-root.crt:/etc/prometheus/certs/hoatranlabs-root.crt:ro
    command:
      - '--config.file=/etc/alertmanager/alertmanager.yml'
      - '--storage.path=/alertmanager'
    networks:
      - monitoring

  node-exporter:
    image: prom/node-exporter:v1.12.1   # cùng bản với script Bước 5
    container_name: node-exporter
    restart: unless-stopped
    # Theo hướng dẫn chính thức của node_exporter khi chạy trong container: dùng namespace mạng và PID của host,
    # mount thư mục gốc của host vào /host (chỉ đọc) và trỏ --path.rootfs tới đó, để node_network_*, tiến trình, ổ đĩa
    # là của VM chứ không phải của container. Không dùng `ports`/`networks`: node_exporter nghe thẳng cổng 9100 của VM.
    network_mode: host
    pid: host
    volumes:
      - /:/host:ro,rslave
    command:
      - '--path.rootfs=/host'

networks:
  monitoring:
    driver: bridge

volumes:
  alertmanager_data:
    driver: local
EOF

Retention và dung lượng đĩa. Công thức trong tài liệu Prometheus: dung_lượng ≈ thời_gian_giữ (giây) × mẫu_mỗi_giây × 1–2 byte. Lab có khoảng 35 target × ~1.200 series (node_exporter) scrape mỗi 15 giây ≈ 2.800 mẫu/giây, nên 15 ngày ≈ 1,3 triệu giây × 2.800 × 1,5 byte ≈ 5,4 GB; cộng pve-exporter, remote_write từ K3s (bài 28) và WAL thì làm tròn thành retention.size=8GB. Đây là ước tính: sau 1–2 ngày chạy hãy đo bằng du -sh /opt/prometheus/data và truy vấn rate(prometheus_tsdb_head_samples_appended_total[1h]) rồi tính lại. Giới hạn 8 GB cũng vừa với đĩa disk 40 GB của VM235 (hệ điều hành + Docker + image ≈ 17 GB, bài 07 mục 8.6); tài liệu Prometheus khuyên đặt retention.size tối đa 80–85% phần đĩa dành cho TSDB vì WAL được tính vào giới hạn và compaction tạm vượt giới hạn, còn khi đặt cả time lẫn size thì giới hạn nào chạm trước sẽ được áp dụng. Muốn giữ 30 ngày thì cần khoảng 2 lần dung lượng (≈ 16 GB): nới đĩa SSD bằng qm resize 235 scsi0 +20G (lệnh trong VM: growpart + resize2fs, hoặc pvresize + lvextend nếu dùng LVM, như bài 33 mục 1.1) rồi tăng retention.time/retention.size tương ứng. TSDB nên nằm ở /opt/prometheus/data trên đĩa SSD (không đặt lên HDD vm-bulk: bài 07 mục 8.5).

Khởi động Prometheus và Alertmanager:

cd /opt/prometheus
docker compose up -d
docker compose ps

Kiểm tra Prometheus và Alertmanager đã chạy:

curl -s http://10.11.45.35:9090/-/healthy
# Kết quả mong đợi: Prometheus Server is Healthy.

curl -s http://10.11.45.35:9093/-/healthy
# Kết quả mong đợi: OK
Terminal VM235 trong /opt/prometheus: `docker compose ps` cho prometheus, alertmanager, node-exporter đều Up; `curl :9090/-/healthy` trả Prometheus Server is Healthy. và `curl :9093/-/healthy` trả OK.
Terminal VM235 trong /opt/prometheus: `docker compose ps` cho prometheus, alertmanager, node-exporter đều Up; `curl :9090/-/healthy` trả Prometheus Server is Healthy. và `curl :9093/-/healthy` trả OK.

Mở cổng Alertmanager trên VM235 (nếu dùng ufw; UI/API cho VLAN_MGMT, các VM VLAN khác gửi alert thẳng vào API thì thêm rule tương ứng):

ufw allow from 10.11.45.0/24 to any port 9093 proto tcp comment "Alertmanager"

Gửi email thử qua Alertmanager (chạy SAU KHI Mailu ở bài 16 đã hoạt động; alert sẽ được gom nhóm và gửi sau khoảng group_wait 30 giây):

docker exec alertmanager amtool alert add alertname=TestMail severity=warning \
  --annotation=summary="Test email Alertmanager qua Mailu" \
  --alertmanager.url=http://localhost:9093
docker logs alertmanager --tail 20
03

Tạo VM236 (Grafana Stack)

Cách 1: Web UI Proxmox (GUI)

1
Đăng nhập Proxmox Web UI → chọn Node: node2 → nhấn Create VM (góc trên phải)
2
General:
  • VM ID: 236
  • Name: grafana
  • Bỏ tick Start after created
3
OS:
  • Storage: local (hoặc nơi chứa ISO)
  • ISO Image: ubuntu-24.04.5-live-server-amd64.iso
  • Guest OS Type: Linux, Version: 6.x - 2.6 Kernel
4
System:
  • Machine: q35
  • SCSI Controller: VirtIO SCSI single
  • BIOS: SeaBIOS
  • Qemu Agent: ☑
5
Disks:
  • Bus/Device: SCSI 0, Storage: vm-ceph (thường là vm-ceph)
  • Disk size: 20 GiB (đúng cột disk của bài 07), Cache: Write back, Discard: ☑
6
CPU:
  • Sockets: 1, Cores: 4, Type: x86-64-v2-AES
7
Memory:
  • Memory (MiB): 4096
8
Network:
  • Bridge: vmbr0, VLAN Tag: 45, Model: VirtIO (paravirtualized), Firewall: ☐
9
Confirm: Xem lại → Finish → Start VM → Console để bắt đầu cài Ubuntu.

Cách 2: CLI (qm create)

qm create 236 \
  --name grafana \
  --memory 4096 \
  --cores 4 \
  --net0 virtio,bridge=vmbr0,tag=45 \
  --scsi0 vm-ceph:20 \
  --scsihw virtio-scsi-pci \
  --ide2 local:iso/ubuntu-24.04.5-live-server-amd64.iso,media=cdrom \
  --boot "order=ide2;scsi0" \
  --ostype l26 \
  --agent enabled=1 \
  --onboot 1 \
  --startup order=4,up=30

Cài đặt OS Ubuntu Server 24.04 LTS:

Hostname    : grafana
Username    : sysadmin
Password    : <mật khẩu mạnh>
IP          : 10.11.45.36/24
Gateway     : 10.11.45.1
DNS         : 10.11.45.53

Sau khi cài xong, eject ISO bằng qm set 236 --ide2 none. Cài Docker tương tự VM235 (lặp lại các bước cài Docker từ repo noble ở Bước 1).

04

Triển Khai Grafana + Uptime Kuma + Gotify trên VM236

mkdir -p /opt/grafana-stack && cd /opt/grafana-stack

Tạo thư mục cấu hình:

mkdir -p grafana/provisioning/datasources
mkdir -p grafana/provisioning/dashboards

Tạo datasource provisioning tự động:

cat > /opt/grafana-stack/grafana/provisioning/datasources/prometheus.yml << 'EOF'
apiVersion: 1

datasources:
  - name: Prometheus
    type: prometheus
    access: proxy
    url: http://10.11.45.35:9090
    isDefault: true
    editable: true
    jsonData:
      timeInterval: '15s'
      queryTimeout: '60s'
      httpMethod: 'POST'
EOF

Cài root CA của step-CA lên VM236 (bài 13, Bước 9: chạy distribute-root-ca.sh) trước khi docker compose up; Grafana mount file /usr/local/share/ca-certificates/hoatranlabs-root.crt để tin cậy Mailu và Authentik.

Tạo docker-compose.yml cho VM236:

cat > /opt/grafana-stack/docker-compose.yml << 'EOF'
# Không khai báo `version:` (obsolete), giống VM235
services:
  grafana:
    image: grafana/grafana:latest
    container_name: grafana
    restart: unless-stopped
    ports:
      - "3000:3000"
    environment:
      - GF_SECURITY_ADMIN_USER=admin
      - GF_SECURITY_ADMIN_PASSWORD=Admin@HoatranLabs2024
      - GF_USERS_ALLOW_SIGN_UP=false
      - GF_SERVER_ROOT_URL=http://grafana.hoatranlabs.local:3000
      - GF_AUTH_GENERIC_OAUTH_ENABLED=true
      - GF_AUTH_GENERIC_OAUTH_NAME=Authentik
      - GF_AUTH_GENERIC_OAUTH_CLIENT_ID=REPLACE_WITH_AUTHENTIK_CLIENT_ID
      - GF_AUTH_GENERIC_OAUTH_CLIENT_SECRET=REPLACE_WITH_AUTHENTIK_CLIENT_SECRET
      - GF_AUTH_GENERIC_OAUTH_SCOPES=openid email profile
      - GF_AUTH_GENERIC_OAUTH_AUTH_URL=https://authentik.hoatranlabs.local:9443/application/o/authorize/
      - GF_AUTH_GENERIC_OAUTH_TOKEN_URL=https://authentik.hoatranlabs.local:9443/application/o/token/
      - GF_AUTH_GENERIC_OAUTH_API_URL=https://authentik.hoatranlabs.local:9443/application/o/userinfo/
      # Nhóm Authentik `grafana-admin` (tạo ở bài 14 mục 8.2) -> role Admin, user khác -> Viewer.
      # Claim `groups` đi kèm scope `profile` (đã có trong GF_AUTH_GENERIC_OAUTH_SCOPES ở trên)
      - GF_AUTH_GENERIC_OAUTH_ROLE_ATTRIBUTE_PATH=contains(groups[*], 'grafana-admin') && 'Admin' || 'Viewer'
      # SMTP: dùng Mailu (bài 16) - 587 STARTTLS có xác thực, tài khoản dịch vụ noreply@
      - GF_SMTP_ENABLED=true
      - GF_SMTP_HOST=mailu.hoatranlabs.local:587
      - [email protected]
      - GF_SMTP_PASSWORD=Noreply@Mailu2024!
      - [email protected]
      - GF_SMTP_FROM_NAME=Grafana Lab
      - GF_SMTP_STARTTLS_POLICY=MandatoryStartTLS
      - GF_SMTP_SKIP_VERIFY=false
    volumes:
      - grafana_data:/var/lib/grafana
      - ./grafana/provisioning:/etc/grafana/provisioning:ro
      # Root CA của step-CA (bài 13): để Grafana tin cậy chứng chỉ của Mailu (SMTP) và Authentik (OIDC).
      # Mount vào /etc/ssl/certs (thư mục tin cậy mà Grafana đọc); /usr/local/share/ca-certificates trong container không tự được nạp
      - /usr/local/share/ca-certificates/hoatranlabs-root.crt:/etc/ssl/certs/hoatranlabs-root.crt:ro
    networks:
      - monitoring

  uptime-kuma:
    image: louislam/uptime-kuma:latest
    container_name: uptime-kuma
    restart: unless-stopped
    ports:
      - "3001:3001"
    volumes:
      - kuma_data:/app/data
    networks:
      - monitoring

  gotify:
    image: gotify/server:latest
    container_name: gotify
    restart: unless-stopped
    ports:
      - "3002:80"
    environment:
      - GOTIFY_DEFAULTUSER_NAME=admin
      - GOTIFY_DEFAULTUSER_PASS=Admin@Gotify2024
    volumes:
      - gotify_data:/app/data
    networks:
      - monitoring

  node-exporter:
    image: prom/node-exporter:v1.12.1   # cùng bản với script Bước 5
    container_name: node-exporter
    restart: unless-stopped
    # Như VM235: host network + pid host + mount / vào /host để số liệu là của VM (không dùng `ports`/`networks`)
    network_mode: host
    pid: host
    volumes:
      - /:/host:ro,rslave
    command:
      - '--path.rootfs=/host'

networks:
  monitoring:
    driver: bridge

volumes:
  grafana_data:
    driver: local
  kuma_data:
    driver: local
  gotify_data:
    driver: local
EOF

Khởi động stack:

cd /opt/grafana-stack
docker compose up -d
docker compose ps
Terminal VM236: `docker compose ps` hiện grafana (3000), uptime-kuma (3001), gotify (3002→80), node-exporter (host network, :9100) đều Up.
Terminal VM236: `docker compose ps` hiện grafana (3000), uptime-kuma (3001), gotify (3002→80), node-exporter (host network, :9100) đều Up.
05

Cài node_exporter trên TẤT CẢ các VM

Chạy script sau trên mỗi VM Linux (và 4 node PVE) để Prometheus có thể scrape metrics.

Loại trừ và lưu ý:

  • VM235 (prometheus) và VM236 (grafana): đã có container node-exporter chạy network_mode: host và nghe thẳng cổng 9100 của VM (Bước 2 và Bước 4), KHÔNG chạy script này (sẽ trùng cổng 9100). Script có sẵn đoạn tự bỏ qua hai VM này theo hostname. Vì container dùng host network nên cổng 9100 do UFW của VM kiểm soát (khác cổng Docker ports): nếu bật UFW trên hai VM này, mở cổng như lệnh ufw allow ở cuối Bước 5; riêng VM235, Prometheus (container, mạng Docker) scrape chính IP 10.11.45.35 nên cần thêm nguồn là dải mạng Docker, thường 172.16.0.0/12.
  • VM250 (dc1): không bị loại trừ — là Samba AD DC chạy Ubuntu 24.04 (bài 25) nên cài node_exporter bằng script này như mọi VM Linux khác (UFW trên dc1 phải cho Prometheus 10.11.45.35 vào cổng 9100, đã mở ở bài 25).
  • ops01 (VM290, 10.11.45.20): máy quản trị/tự động hoá tạo ở bài 07 (Ubuntu 24.04), cài bằng script này như VM Linux khác và đã có trong job vlan-mgmt-vms. Nếu bài 07 đã cài sẵn node_exporter cho ops01 (ví dụ qua cloud-init), script ghi đè cùng đường dẫn /usr/local/bin/node_exporter và service cùng tên nên chạy lại vẫn an toàn.
  • Script này là NGUỒN của lab: các bài khác chỉ tham chiếu install-node-exporter.sh, phiên bản node_exporter dùng chung là 1.12.1 (đối chiếu release v1.12.1 ngày 2026-07-14 và sha256sums.txt của bản phát hành).
#!/bin/bash
# install-node-exporter.sh
# Chạy với quyền root trên từng VM Ubuntu 24.04 (và 4 node PVE; trừ VM235/VM236 - xem ghi chú trên)

set -euo pipefail

# VM235 (prometheus) và VM236 (grafana) đã có container node-exporter ở cổng 9100 -> bỏ qua
case "$(hostname -s)" in
  prometheus|grafana)
    echo "VM235/VM236 đã có container node-exporter (cổng 9100) -> bỏ qua script này."
    exit 0
    ;;
esac

NODE_EXPORTER_VERSION="1.12.1"
ARCH="amd64"
# SHA-256 của node_exporter-1.12.1.linux-amd64.tar.gz (trích từ sha256sums.txt của release v1.12.1, đối chiếu 2026-10-15).
# Đổi phiên bản/kiến trúc thì phải lấy lại giá trị này từ sha256sums.txt của đúng release.
NODE_EXPORTER_SHA256="b51d8a76aa2a9156a55d501aca6276fae09e262259a5e4e831d2c2222f084e63"

echo "[1/6] Tải node_exporter v${NODE_EXPORTER_VERSION}..."
cd /tmp
TARBALL="node_exporter-${NODE_EXPORTER_VERSION}.linux-${ARCH}.tar.gz"
wget -q "https://github.com/prometheus/node_exporter/releases/download/v${NODE_EXPORTER_VERSION}/${TARBALL}"
echo "${NODE_EXPORTER_SHA256}  ${TARBALL}" | sha256sum -c -

echo "[2/6] Giải nén..."
tar xzf "${TARBALL}"

echo "[3/6] Copy binary..."
systemctl stop node_exporter 2>/dev/null || true   # nếu đang chạy bản cũ (nâng cấp từ 1.8.2): dừng trước khi ghi đè
cp "node_exporter-${NODE_EXPORTER_VERSION}.linux-${ARCH}/node_exporter" /usr/local/bin/
chmod 755 /usr/local/bin/node_exporter

echo "[4/6] Tạo user node_exporter..."
id node_exporter &>/dev/null || useradd -rs /usr/sbin/nologin node_exporter

echo "[5/6] Tạo systemd service..."
cat > /etc/systemd/system/node_exporter.service << 'SVCEOF'
[Unit]
Description=Prometheus Node Exporter
Documentation=https://prometheus.io/docs/guides/node-exporter/
After=network-online.target

[Service]
User=node_exporter
Group=node_exporter
Type=simple
Restart=on-failure
RestartSec=5s
ExecStart=/usr/local/bin/node_exporter \
  --collector.cpu \
  --collector.diskstats \
  --collector.filesystem \
  --collector.loadavg \
  --collector.meminfo \
  --collector.netdev \
  --collector.processes \
  --web.listen-address=:9100

[Install]
WantedBy=multi-user.target
SVCEOF

echo "[6/6] Kích hoạt service..."
systemctl daemon-reload
systemctl enable --now node_exporter

rm -rf "/tmp/${TARBALL}" "/tmp/node_exporter-${NODE_EXPORTER_VERSION}.linux-${ARCH}"
echo "Done. Kiểm tra: /usr/local/bin/node_exporter --version | head -1 ; curl -s http://localhost:9100/metrics | head -5"
Script chỉ dành cho amd64 (SHA-256 ở trên là của bản amd64). Cùng script dùng cho 4 node PVE (Debian 13) vì bản phát hành là một binary Go độc lập, không phụ thuộc phiên bản glibc của Ubuntu 24.04; việc chạy trên node PVE 9 cần kiểm lại trên máy thật.

Cấp quyền thực thi và chạy:

chmod +x install-node-exporter.sh
bash install-node-exporter.sh

Mở port firewall (nếu dùng ufw):

ufw allow from 10.11.45.35 to any port 9100 proto tcp
Prometheus UI http://10.11.45.35:9090/targets (Status → Targets): các job pve-nodes, vlan-mgmt-vms (gồm ops01 10.11.45.20), vlan-sec-vms, vlan-dmz-vms, vlan-srv-vms, vlan-storage-vms ở trạng thái UP sau khi cài node_exporter 1.12.1.
Prometheus UI http://10.11.45.35:9090/targets (Status → Targets): các job pve-nodes, vlan-mgmt-vms (gồm ops01 10.11.45.20), vlan-sec-vms, vlan-dmz-vms, vlan-srv-vms, vlan-storage-vms ở trạng thái UP sau khi cài node_exporter 1.12.1.
06

Cấu Hình Grafana Dashboard

Truy cập Grafana: http://10.11.45.36:3000
Login: admin / Admin@HoatranLabs2024

Import dashboard Node Exporter Full (ID: 1860):

1
Vào Dashboards → Import
2
Nhập ID: 1860 → Load
3
Chọn datasource: Prometheus
4
Nhấn Import
Grafana → Dashboards → Node Exporter Full (ID 1860): biểu đồ CPU, RAM, disk, network của một node với datasource Prometheus.
Grafana → Dashboards → Node Exporter Full (ID 1860): biểu đồ CPU, RAM, disk, network của một node với datasource Prometheus.

Import dashboard Docker + Containers:

  1. Vào Dashboards → Import
  2. Nhập ID: 11600 → Load
  3. Chọn datasource: Prometheus
  4. Nhấn Import
07

Cấu Hình Uptime Kuma

Truy cập: http://10.11.45.36:3001
Tạo tài khoản admin lần đầu.

Thêm monitors cho các service chính:

Monitor NameTypeURL/AddressPortInterval
PrometheusHTTPhttp://10.11.45.35:9090/-/healthy—60s
GrafanaHTTPhttp://10.11.45.36:3000/api/health—60s
Pi-holeHTTPhttp://10.11.45.53/admin—60s
AuthentikHTTPhttp://10.11.25.40:9000/-/health/live/—60s
GotifyHTTPhttp://10.11.45.36:3002/health—60s
PVE node1TCP10.11.45.210800660s
PVE node2TCP10.11.45.211800660s
PVE node3TCP10.11.45.212800660s
PVE node4TCP10.11.45.213800660s
Uptime Kuma tại http://10.11.45.36:3001: danh sách monitor Prometheus, Grafana, Pi-hole, Authentik, Gotify và 4 node PVE đều Up.
Uptime Kuma tại http://10.11.45.36:3001: danh sách monitor Prometheus, Grafana, Pi-hole, Authentik, Gotify và 4 node PVE đều Up.

Kết nối Gotify notification trong Uptime Kuma:

1
Vào Settings → Notifications → Add Notification
2
Chọn type: Gotify
3
Server URL: http://10.11.45.36:3002
4
Application Token: _(lấy từ Gotify app token, xem Bước 8)_
5
Test notification → Save
Uptime Kuma → Settings → Notifications: thông báo kiểu Gotify với Server URL http://10.11.45.36:3002, Application Token đã che.
Uptime Kuma → Settings → Notifications: thông báo kiểu Gotify với Server URL http://10.11.45.36:3002, Application Token đã che.
08

Cấu Hình Gotify

Truy cập: http://10.11.45.36:3002
Login: admin / Admin@Gotify2024

Tạo Application token:

  1. Vào Apps → Create Application
  2. Name: uptime-kuma
  3. Copy token → dùng trong Bước 7

Tạo Application token cho Grafana:

1
Vào Apps → Create Application
2
Name: grafana-alerts
3
Copy token
Gotify tại http://10.11.45.36:3002 → Apps: hai ứng dụng uptime-kuma và grafana-alerts đã tạo (che token trước khi đăng).
Gotify tại http://10.11.45.36:3002 → Apps: hai ứng dụng uptime-kuma và grafana-alerts đã tạo (che token trước khi đăng).

Cấu hình Grafana Alerting → Notification Channel:

Trong Grafana: Alerting → Contact Points → Add contact point

Name: Gotify
Type: Webhook
URL: http://10.11.45.36:3002/message?token=<GRAFANA_APP_TOKEN>
HTTP Method: POST
Grafana → Alerting → Contact points: contact point Gotify kiểu Webhook, URL .../message?token=..., HTTP Method POST (che token).
Grafana → Alerting → Contact points: contact point Gotify kiểu Webhook, URL .../message?token=..., HTTP Method POST (che token).
09

Cấu Hình DNS và Firewall

Thêm A records trong Pi-hole:

Vào Pi-hole admin → Settings → Local DNS Records:

DomainIP
prometheus.hoatranlabs.local10.11.45.35
grafana.hoatranlabs.local10.11.45.36
kuma.hoatranlabs.local10.11.45.36
gotify.hoatranlabs.local10.11.45.36
Pi-hole Admin → Settings → Local DNS Records (khung Local DNS records): prometheus.hoatranlabs.local → 10.11.45.35; grafana, kuma và gotify .hoatranlabs.local → 10.11.45.36.
Pi-hole Admin → Settings → Local DNS Records (khung Local DNS records): prometheus.hoatranlabs.local → 10.11.45.35; grafana, kuma và gotify .hoatranlabs.local → 10.11.45.36.

Quy tắc firewall trên FortiGate:

NguồnĐíchPortMục đích
10.11.45.35All VMs9100/tcpPrometheus scrape
10.11.45.0/2410.11.45.359090/tcpGrafana → Prometheus
10.11.65.60-65 (K3s)10.11.45.359090/tcpremote_write từ K3s (bài 28)
10.11.45.0/2410.11.45.359093/tcpAlertmanager UI/API (VM VLAN khác gửi alert trực tiếp thì thêm nguồn tương ứng)
10.11.45.3510.11.45.210-213 (node1–node4)8006/tcppve-exporter (Bước 11) gọi API Proxmox; cùng VLAN 45, chỉ cần mở nếu node bật firewall PVE (bài 05)
10.11.45.3510.11.45.210 (node1, máy chủ NUT)3493/tcpnut_exporter (Bước 11) đọc số liệu UPS từ upsd (bài 10)
10.11.45.3510.11.35.46587/tcpAlertmanager → Mailu (SMTP STARTTLS)
10.11.45.3610.11.35.46587/tcpGrafana → Mailu (SMTP STARTTLS)
10.11.45.3510.11.65.66 (SonarQube)443/tcpPrometheus scrape /api/monitoring/metrics qua Nginx (bài 30)
10.11.45.3510.11.65.67 (Nexus)443/tcpPrometheus scrape /service/rest/metrics/prometheus qua Nginx (bài 31)
10.11.45.3510.11.85.10 (SeaweedFS S3, qua Nginx s3.hoatranlabs.local)443/tcpPrometheus scrape metrics SeaweedFS (jobs s3*, đường dẫn /_metrics/*, bài 32)
10.11.45.358 VM chạy Alloy12345/tcpPrometheus scrape Alloy (bài 33)
8 VM chạy Alloy10.11.45.353100/tcpAlloy đẩy log vào Loki (bài 33)
Admin VLAN10.11.45.363000,3001,3002/tcpWeb UI access
10

Cấu Hình Backup PBS

Đăng nhập PVE → Datacenter → Backup → Add:

Node        : node2
Storage     : pbs-primary (pbs01, 10.11.45.17)
Schedule    : daily 03:30
VMs         : 235, 236
Mode        : Snapshot
Retention   : mặc định (retention do Prune Job trên PBS quản lý, bài 04 mục 7)
Proxmox Datacenter → Backup: job daily 03:30 trên node2, storage pbs-primary, VM 235 và 236, mode Snapshot, keep-daily=7, keep-weekly=4.
Proxmox Datacenter → Backup: job daily 03:30 trên node2, storage pbs-primary, VM 235 và 236, mode Snapshot, keep-daily=7, keep-weekly=4.
11

Giám sát Proxmox VE và UPS (tuỳ chọn, tham chiếu bài 08 và bài 10)

Mục này chỉ là tham chiếu và cấu hình mẫu: token API do bài 08 tạo, máy chủ NUT do bài 10 dựng. Cả hai bài nằm TRƯỚC bài 15 trong lộ trình nên có thể đã sẵn sàng; nếu chưa, bỏ qua Bước 11 (và comment 3 job pve, pve-per-node, nut trong prometheus.yml). Hai exporter chạy thành container trên VM235, cùng mạng Docker monitoring với Prometheus nên không cần publish cổng ra ngoài VM.

ExporterNguồn số liệuJob trong prometheus.ymlCổng (nội bộ)
prometheus-pve-exporter 3.10.1API Proxmox VE https://nodeN.hoatranlabs.local:8006 bằng token svc-monitoring@pve!prometheus (bài 08)pve (cấp cụm, 1 node) và pve-per-node (cấp node, node1–node4)9221
nut_exporter 3.3.0Máy chủ NUT (upsd) trên node1 10.11.45.210:3493, UPS ups01 10.11.45.19 (bài 10)nut9199

11.1 Quyền cho token (đã làm ở bài 08, ghi lại để đối chiếu). Token dùng quyền chỉ đọc. svc-monitoring@pve!prometheus bật privilege separation nên ACL phải gán cho cả user và token (quyền hiệu lực là phần giao của hai bên). Role PVEAuditor trên / là yêu cầu của prometheus-pve-exporter; nếu bài 08 đặt role tuỳ chỉnh AuditReadOnly thì dùng đúng role đó (bảo đảm có quyền xem tài nguyên và storage):

# Chạy trên một node PVE. Bỏ qua nếu bài 08 đã tạo user, token và ACL
pveum acl modify / --users svc-monitoring@pve --roles PVEAuditor
pveum acl modify / --tokens 'svc-monitoring@pve!prometheus' --roles PVEAuditor

Secret của token chỉ hiện một lần lúc tạo; đặt vào file env bên dưới, KHÔNG ghi vào prometheus.yml hay Git.

11.2 File cấu hình exporter trên VM235:

mkdir -p /opt/prometheus/pve-exporter
cat > /opt/prometheus/pve-exporter/pve.env << 'EOF'
PVE_USER=svc-monitoring@pve
PVE_TOKEN_NAME=prometheus
PVE_TOKEN_VALUE=<TOKEN_SECRET>
# true khi cert của node đã do step-CA cấp (bài 09). Chưa có thì tạm đặt false (chứng chỉ tự ký mặc định của PVE)
PVE_VERIFY_SSL=true
EOF
chmod 600 /opt/prometheus/pve-exporter/pve.env

Theo README của prometheus-pve-exporter, khi có biến PVE_USER thì exporter đọc cấu hình từ biến môi trường (module default) và bỏ qua file pve.yml.

11.3 Thêm hai service vào /opt/prometheus/docker-compose.yml (dưới khối services:, cùng cấp với prometheus, alertmanager, node-exporter):

pve-exporter:
    image: prompve/prometheus-pve-exporter:3.10.1
    container_name: pve-exporter
    restart: unless-stopped
    env_file: ./pve-exporter/pve.env
    environment:
      # Tin cậy root CA step-CA khi PVE_VERIFY_SSL=true (cần kiểm lại trên máy thật: thư viện requests đọc biến này)
      - REQUESTS_CA_BUNDLE=/etc/prometheus/certs/hoatranlabs-root.crt
    volumes:
      - /usr/local/share/ca-certificates/hoatranlabs-root.crt:/etc/prometheus/certs/hoatranlabs-root.crt:ro
    networks:
      - monitoring

  nut-exporter:
    image: druggeri/nut_exporter:3.3.0
    container_name: nut-exporter
    restart: unless-stopped
    command:
      - '--nut.server=10.11.45.210'      # node1: máy chủ NUT (upsd) của bài 10
      - '--web.listen-address=:9199'
    networks:
      - monitoring

upsd mặc định chỉ lắng nghe 127.0.0.1: bài 10 phải cho upsd lắng nghe 10.11.45.210:3493 và firewall node1 phải cho 10.11.45.35 vào cổng 3493 thì nut_exporter mới đọc được. Số liệu UPS lấy qua NUT chứ không quét SNMP trực tiếp vào ups01.

11.4 Áp dụng và kiểm tra:

cd /opt/prometheus
docker compose up -d
docker compose ps
curl -X POST http://10.11.45.35:9090/-/reload

# Gọi exporter từ trong mạng Docker (image prom/prometheus có sẵn wget)
docker exec prometheus wget -qO- 'http://pve-exporter:9221/pve?target=node1.hoatranlabs.local&cluster=1&node=0' | head -5
docker exec prometheus wget -qO- 'http://nut-exporter:9199/ups_metrics?ups=ups01' | head -5

Kết quả mong đợi (mẫu): có các dòng pve_up{...}, pve_node_info{...} và các dòng metric network_ups_tools_*. Vào Prometheus UI → Status → Targets: job pve, pve-per-node (4 target) và nut ở trạng thái UP. Nếu pve-exporter trả HTTP 401/403: token hoặc ACL sai (mục 11.1); lỗi certificate verify failed: node chưa có cert hợp lệ cho tên FQDN (bài 09) hoặc root CA chưa cài, tạm đặt PVE_VERIFY_SSL=false.

Terminal VM235: `docker compose ps` có thêm pve-exporter và nut-exporter ở trạng thái Up; hai lệnh `docker exec prometheus wget ...` in ra metric pve_up/pve_node_info và network_ups_tools_* (che token). Prometheus UI → Status → Targets: job pve, pve-per-node (4 target) và nut đều UP.
Terminal VM235: `docker compose ps` có thêm pve-exporter và nut-exporter ở trạng thái Up; hai lệnh `docker exec prometheus wget ...` in ra metric pve_up/pve_node_info và network_ups_tools_* (che token). Prometheus UI → Status → Targets: job pve, pve-per-node (4 target) và nut đều UP.

11.5 Rule cảnh báo mẫu (đặt vào /opt/prometheus/rules/proxmox.yml, rồi curl -X POST http://10.11.45.35:9090/-/reload; tên metric kiểm lại trên /pve và /ups_metrics của phiên bản đang chạy):

groups:
  - name: proxmox
    rules:
      - alert: PVENodeDown
        expr: pve_up{id=~"node/.*"} == 0
        for: 2m
        labels:
          severity: critical
        annotations:
          summary: "Node Proxmox {{ $labels.id }} không phản hồi"
      - alert: NutExporterDown
        expr: up{job="nut"} == 0
        for: 5m
        labels:
          severity: warning
        annotations:
          summary: "Không đọc được số liệu UPS (nut_exporter hoặc máy chủ NUT trên node1)"

Chuỗi cảnh báo hết pin/mất điện lưới và tắt máy tuần tự nằm ở bài 10 (NUT upsmon), không thay thế bằng Prometheus: Prometheus chỉ để quan sát xu hướng và gửi email qua Alertmanager.

Xác Nhận Hoạt Động (Verification Checklist)

# Kiểm tra Prometheus targets
curl -s http://10.11.45.35:9090/api/v1/targets | python3 -m json.tool | grep '"health"'

# Kiểm tra Alertmanager (container alertmanager, cổng 9093)
curl -s http://10.11.45.35:9093/-/healthy

# Kiểm tra Grafana API (/api/health không cần đăng nhập)
curl -s http://10.11.45.36:3000/api/health

# Kiểm tra node_exporter trả về metrics
curl -s http://10.11.45.35:9100/metrics | grep node_cpu_seconds_total | head -3

# Số liệu mạng phải là của VM (NIC thật như ens18/enp6s18), không chỉ eth0/lo của container
curl -s http://10.11.45.35:9100/metrics | grep '^node_network_up'

# Kiểm tra container status
docker ps --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"
Terminal: kết quả kiểm tra gồm targets có "health": "up", Alertmanager :9093/-/healthy trả OK, Grafana /api/health, metric node_cpu_seconds_total và docker ps.
Terminal: kết quả kiểm tra gồm targets có "health": "up", Alertmanager :9093/-/healthy trả OK, Grafana /api/health, metric node_cpu_seconds_total và docker ps.

Xử Lý Sự Cố (Troubleshooting)

Prometheus không scrape được target:

# Kiểm tra kết nối từ VM235 đến target
curl -v http://10.11.45.36:9100/metrics

# Reload Prometheus config không cần restart
curl -X POST http://10.11.45.35:9090/-/reload

# Xem log Prometheus
docker logs prometheus --tail 50

# Log báo "permission denied" ở /prometheus (TSDB bind mount): thư mục phải thuộc user nobody (UID 65534)
chown -R 65534:65534 /opt/prometheus/data && docker compose -f /opt/prometheus/docker-compose.yml restart prometheus

Grafana không kết nối được Prometheus:

# Kiểm tra routing giữa VM236 và VM235
ping 10.11.45.35
telnet 10.11.45.35 9090

# Kiểm tra datasource trong Grafana (dùng -u vì mật khẩu có ký tự @ không đặt được trong URL)
curl -s -u 'admin:Admin@HoatranLabs2024' http://10.11.45.36:3000/api/datasources

Uptime Kuma không gửi được notification:

# Kiểm tra Gotify log
docker logs gotify --tail 20

# Kiểm tra port 3002
ss -tlnp | grep 3002

node_exporter không start:

journalctl -u node_exporter -n 20
systemctl status node_exporter
# Lỗi `sha256sum: WARNING: 1 computed checksum did NOT match` khi chạy script: tải lại tarball hoặc đối chiếu NODE_EXPORTER_SHA256
# với sha256sums.txt của đúng release (github.com/prometheus/node_exporter/releases)

apt hiện hộp thoại khi cài gói trên Ubuntu 24.04: needrestart có thể hiện hộp thoại chọn dịch vụ cần khởi động lại khi chạy apt trong script; đặt NEEDRESTART_MODE=a (đã có ở Bước 1) hoặc chọn OK để dùng mặc định.

Checklist Hoàn Thành

  • VM235 (prometheus) tạo thành công, IP 10.11.45.35/24
  • VM236 (grafana) tạo thành công, IP 10.11.45.36/24
  • Prometheus scrape được tất cả targets (status=UP)
  • VM235/VM236 chạy Ubuntu Server 24.04 LTS, Docker cài từ repo noble (docker --version, docker compose version)
  • node_exporter 1.12.1 cài trên tất cả 30 VMs + 4 PVE nodes + ops01 (VM290) (VM235/VM236 dạng container có sẵn; VM250 dc1 là Samba AD DC trên Ubuntu 24.04 nên cài như các VM Linux khác); node_exporter --version báo 1.12.1
  • Alertmanager (container alertmanager, cổng 9093, cấu hình /opt/prometheus/alertmanager/alertmanager.yml) chạy và gửi được email thử qua Mailu ([email protected])
  • Grafana import dashboard 1860 thành công
  • Grafana kết nối Authentik OIDC
  • Uptime Kuma monitors cho tất cả service quan trọng
  • Gotify nhận notification từ Uptime Kuma
  • DNS A records: prometheus.hoatranlabs.local, grafana.hoatranlabs.local, kuma.hoatranlabs.local, gotify.hoatranlabs.local
  • Firewall cho phép port 9100 từ 10.11.45.35
  • Backup PBS định kỳ cho VM235, VM236
  • Prometheus retention 15 ngày / 8 GB (du -sh /opt/prometheus/data dưới 8 GB) hoạt động bình thường
  • (Tuỳ chọn, Bước 11) Job pve, pve-per-node và nut UP; token svc-monitoring@pve!prometheus chỉ có quyền đọc

Tài Liệu Tham Khảo

Zalo