System & Network SonarQube SAST
Bài 30 · Giai đoạn 6 — DevOps Platform

SonarQube Community SAST

Code quality & security analysis — tích hợp Gitea CI pipeline.

VM266 · node2 Ubuntu Server 24.04 LTS 10.11.65.66 4 vCPU · 8 GB · 30 GB

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

Vị trí trong chuỗi bài: Bài 30 thuộc Giai đoạn 6 — DevOps Platform, nối tiếp Bài 29. ArgoCD GitOps và đứng trước Bài 31. Nexus Repository.
Mức độ cần thiết: 🟡 Quan trọng — Phân tích chất lượng code tự động, phát hiện bug và lỗ hổng bảo mật sớm trong quá trình phát triển

SonarQube là nền tảng phân tích tĩnh code (static analysis) giúp phát hiện bug, code smells, security vulnerabilities, và technical debt ngay trong quá trình phát triển. Khi tích hợp với Gitea Actions, mỗi lần developer push code lên nhánh chính (main) của Gitea, workflow gọi scanner để SonarQube tự động phân tích và báo cáo Quality Gate — nếu code có lỗi nghiêm trọng, pipeline sẽ fail. Bản Community chỉ phân tích nhánh chính; phân tích nhánh phụ và Pull Request (kèm chặn merge theo Quality Gate) là tính năng từ Developer Edition trở lên.

Community Edition (từ bản 25.x SonarSource gọi là Community Build) hỗ trợ phân tích các ngôn ngữ phổ biến (Java, Python, JavaScript/TypeScript, C#, Go, PHP) với SAML SSO. Bài này ghim image sonarqube:26.10.0.133078-community: Community Build phát hành hằng tháng, còn tag lts-community chỉ là bản 9.9.8 cũ (lần cập nhật cuối 09/2025). PostgreSQL 15 được dùng làm database backend (Community Build 26.x hỗ trợ PostgreSQL 15–18), Nginx làm reverse proxy HTTPS. Giám sát dùng endpoint Prometheus tích hợp sẵn của SonarQube (/api/monitoring/metrics), không cần exporter bên ngoài.

MụcNội dung
Ứng dụng trong doanh nghiệpKiểm tra chất lượng code tự động trong CI/CD pipeline
Tác dụng chínhPhát hiện bug, vulnerability, code smell; enforce Quality Gate trên nhánh chính
Nếu không triển khaiReview code thủ công, lỗi bảo mật dễ bị bỏ sót, technical debt tích lũy
Các service phụ thuộc vào đâyGitea CI runner (Gitea Actions, trigger khi push)

Ngày cập nhật: 2026-10-15 (VM sonarqube chạy Ubuntu Server 24.04 LTS; Docker Engine từ kho noble; SonarQube 26.10 và PostgreSQL 15 giữ nguyên)

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
sonarqube (SonarQube Community) · VM26610.11.65.6665 (SRV) · node2Máy chủ của bài — chạy SonarQube Community Build 26.10 và PostgreSQL 15 bằng Docker Compose (metrics từ endpoint tích hợp, không exporter); Nginx làm reverse proxy HTTPS.
node2 (Proxmox VE)10.11.45.21145 (MGMT) · cluster HOATRANHUBNode Proxmox chứa VM266; tải ISO Ubuntu 24.04 và tạo VM bằng Web UI hoặc qm create tại đây.
pihole (Pi-hole DNS) · VM24710.11.45.5345 (MGMT) · node3Phân giải sonarqube.hoatranlabs.local về 10.11.65.66 (bản ghi tạo ở bài 12) và là DNS server đặt trong netplan của VM.
step-ca (step-CA PKI) · VM24210.11.25.4225 (SEC) · node1Cấp chứng chỉ TLS cho Nginx bằng step ca certificate, gia hạn hằng tuần bằng step ca renew + cron (bài 13).
authentik (Authentik SSO) · VM23410.11.25.4025 (SEC) · node1Nhà cung cấp SAML cho nút Log in with Authentik của SonarQube (bài 14).
gitea (Gitea + Actions) · VM24010.11.45.4045 (MGMT) · node2Gitea Actions chạy workflow .gitea/workflows/sonarqube.yaml để quét code và chờ Quality Gate; SONAR_TOKEN và SONAR_ROOT_CERT (root CA cho scanner) lưu trong secret của repo (bài 22).
prometheus (Prometheus + Alertmanager) · VM23510.11.45.3545 (MGMT) · node2Thêm job scrape sonarqube tới /api/monitoring/metrics qua HTTPS cổng 443 (header X-Sonar-Passcode) trong prometheus.yml rồi reload qua cổng 9090 (bài 15).
pbs01 (PBS Primary) · VM10110.11.45.1745 (MGMT) · node4Nhận backup file-level của /opt/sonarqube và /opt/postgresql bằng token vm-backup@pbs!sonarqube, namespace vm-sonarqube (bài 04).
syno-primary (Synology NAS)10.11.45.1645 (MGMT) · NASNAS chứa datastore syno-primary lưu backup của VM; script cron 3:00 hằng ngày, tạm dừng SonarQube khi backup (bài 04).

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.

Thông tin VM

Thông sốGiá trị
VMID266
Hostnamesonarqube
IP10.11.65.66/24
Gateway10.11.65.1
VLAN65 (VLAN_SRV)
vCPU4
RAM8 GB
Disk30 GB (scsi0, SSD vm-ceph)
OSUbuntu Server 24.04 LTS
Phân bổ nodenode2
URLhttps://sonarqube.hoatranlabs.local
Dung lượng đĩa theo kế hoạch lab 800 GB SSD + 1 TB HDD (bài 07, mục 8.4): dựng bằng create-lab-vms.sh thì scsi0 = 30 GB trên SSD vm-ceph, không có đĩa dữ liệu scsi1 (chỉ mục Elasticsearch nhúng trong /opt/sonarqube/data và PostgreSQL trong /opt/postgresql/data cần IOPS ngẫu nhiên nên ở lại SSD); số 30 GB khớp vms.csv và chỉ là trần danh nghĩa (thin provisioning), môi trường thật nên cấp lớn hơn (bài từng ghi 80 GB). Với vài dự án thử, hai thư mục dữ liệu chỉ chiếm vài GB (bài 07 mục 8.6 ước tính image + DB khoảng 3-4 GB); đĩa đầy dần thì hạ log (SONAR_LOG_LEVEL=WARN, mục 6), xóa dự án thử và chạy docker image prune -f.

Phiên bản phần mềm sử dụng (đã xác minh 2026-10-15):

Thành phầnPhiên bản dùng trong bàiGhi chú
Hệ điều hành VM266Ubuntu Server 24.04.5 LTS "Noble Numbat" (ISO ubuntu-24.04.5-live-server-amd64.iso, ngày file 2026-09-09)Kernel 6.8, systemd 255, netplan 1.0, nginx 1.24, Python 3.12, ufw cài sẵn nhưng tắt, cgroup v2; hỗ trợ chuẩn tới 04/2029. Nguồn: releases.ubuntu.com/24.04.
SonarQube Community Build26.10.0.133078 (image sonarqube:26.10.0.133078-community, giữ ghim)Tag có trên Docker Hub (đẩy lên 2026-10-12, là bản mới nhất). SonarQube chạy trong container với JRE đi kèm image, VM không cần cài Java; docs chỉ yêu cầu Java 21 hoặc 25 cho cách cài bằng file ZIP (đã bị đánh dấu deprecated), nên OpenJDK của noble không liên quan bài này.
PostgreSQL15 (image postgres:15-alpine, giữ ghim, chạy trong container)Docs SonarQube Community Build: PostgreSQL 15 đến 18 (từ bản 26.8). Không dùng gói postgresql của noble (PostgreSQL 16) nên không có xung đột.
Docker Engine29.9.1 (kho download.docker.com/linux/ubuntu noble stable; gói docker-ce, docker-ce-cli, containerd.io, docker-buildx-plugin, docker-compose-plugin)Bản mới nhất trong kho noble ngày 2026-10-15 (docs release notes: 29.9.1 ra 2026-10-14). Docker hỗ trợ Ubuntu 24.04 (noble). Lệnh docker compose (plugin v2+).
Nginx1.24 (gói nginx của noble)Reverse proxy HTTPS; cú pháp listen 443 ssl; giữ nguyên.
step CLI0.31.0 (gói .deb)Giá trị dùng chung của lab, cùng bản bài 13 cài (bài 13 dùng step-ca 0.30.2). Cặp CLI 0.31.0 với step-ca 0.30.2 cần kiểm lại trên máy thật.
proxmox-backup-clientproxmox-backup-client-static 4.x, kho pbs-client suite trixieBản liên kết tĩnh nên không phụ thuộc glibc của Ubuntu 24.04; chạy trên noble cần kiểm lại trên máy thật.

Hệ quả của Ubuntu 24.04 đối với bài này: (1) kho Docker khai báo kiểu deb822 docker.sources với suite noble và Signed-By (thay cho docker.list, lsb_release); (2) trình cài ghi mạng vào 50-cloud-init.yaml nên mục 1.4 tắt phần mạng của cloud-init và dùng một file netplan duy nhất; NIC trên VM q35 thường là enp6s18, kiểm bằng ip -br link; (3) needrestart có thể hiện hộp thoại khi apt nên đặt NEEDRESTART_MODE=a; (4) fs.file-max=131072 là mức tối thiểu theo docs SonarSource, kiểm giá trị mặc định của kernel trước khi đặt (mục 1.4); (5) cổng container Docker công bố ra ngoài đi qua iptables và không bị ufw chặn, nên compose của bài chỉ gắn 127.0.0.1:9000 và để Nginx giữ cổng 443.

01

Tạo VM trên Proxmox

Tải Ubuntu ISO (nếu chưa có) · Tạo VM · Cài đặt Ubuntu 24.04

1.1 Tải Ubuntu ISO (nếu chưa có)

# Chạy trên Proxmox node node2
cd /var/lib/vz/template/iso
wget -O ubuntu-24.04-server.iso \
  https://releases.ubuntu.com/24.04/ubuntu-24.04.5-live-server-amd64.iso

# Kiểm tra checksum: so sánh với dòng live-server-amd64 trong SHA256SUMS
wget -qO- https://releases.ubuntu.com/24.04/SHA256SUMS | grep live-server-amd64
sha256sum ubuntu-24.04-server.iso
Dựng nhanh bằng clone template (bài 07): nếu đã có template tpl-ubuntu-2404 (VMID 9000, cloud-init) thì không cần ISO ở mục này, không cần cài tay ở mục 1.3 và có thể bỏ phần hostname/netplan ở mục 1.4. Ví dụ: qm clone 9000 266 --name sonarqube --full 1 --storage vm-ceph --target node2, sau đó qm set 266 --cores 4 --memory 8192 --net0 virtio,bridge=vmbr0,tag=65 --ipconfig0 ip=10.11.65.66/24,gw=10.11.65.1 --nameserver 10.11.45.53 --searchdomain hoatranlabs.local và qm resize 266 scsi0 30G. Các bước sysctl và Docker ở mục 1.4, 2.1 vẫn phải chạy; template tpl-ubuntu-2404-docker (VMID 9001) đã có sẵn Docker Engine thì có thể bỏ mục 2.1 (kiểm lại bản Docker và nguồn kho theo bài 07). Tên đĩa và kích thước template theo bài 07, cần kiểm lại trên máy thật.

1.2 Tạo VM

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: 266
  • Name: sonarqube
  • Bỏ tick Start after created
3
OS:
  • Storage: local (hoặc nơi chứa ISO)
  • ISO Image: ubuntu-24.04-server.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
  • Disk size: 30 GiB, Cache: Write back, Discard: ☑
6
CPU:
  • Sockets: 1, Cores: 4, Type: x86-64-v2-AES
7
Memory:
  • Memory (MiB): 8192
8
Network:
  • Bridge: vmbr0, VLAN Tag: 65, Model: VirtIO (paravirtualized), Firewall: ☐
9
Confirm: Xem lại → Finish → Start VM → Console để bắt đầu cài Ubuntu.
Proxmox Create VM trên node2 → tab Confirm của sonarqube: vmid 266, cores 4, memory 8192, scsi0 vm-ceph:80, net0 virtio vmbr0 tag=65, trước khi bấm Finish.
Proxmox Create VM trên node2 → tab Confirm của sonarqube: vmid 266, cores 4, memory 8192, scsi0 vm-ceph:80, net0 virtio vmbr0 tag=65, trước khi bấm Finish.

Cách 2: CLI (qm create)

# Chạy trên node2
qm create 266 --name sonarqube --memory 8192 --cores 4 --sockets 1 \
  --net0 virtio,bridge=vmbr0,tag=65 \
  --scsi0 vm-ceph:30,cache=writeback \
  --ide2 local:iso/ubuntu-24.04-server.iso,media=cdrom \
  --boot "order=ide2;scsi0" \
  --ostype l26 --machine q35 --bios seabios \
  --agent 1 --serial0 socket --vga serial0
qm start 266

1.3 Cài đặt Ubuntu 24.04

Kết nối qua Proxmox console (qm terminal 266):

  1. Language: English | Keyboard: English (US)
  2. Install type: Ubuntu Server (minimized)
  3. Network: DHCP tạm thời
  4. Storage: entire disk → LVM, không encrypt
  5. Profile: name=sysadmin, server=sonarqube, user=sysadmin, pass=Hoatran@2024!
  6. SSH: ✅ Install OpenSSH server
  7. Snaps: bỏ chọn tất cả → Reboot

Trình cài 24.04 có thêm màn hình Ubuntu Pro (chọn Skip for now) và có thể có màn hình third-party drivers (bỏ qua); tên và thứ tự màn hình có thể khác nhẹ, cần kiểm lại trên máy thật.

1.4 Cấu hình sau cài đặt

# SSH vào VM: ssh sysadmin@<dhcp-ip> rồi sudo -i (các lệnh dưới chạy bằng root)
# Update. Ubuntu 24.04 có needrestart: NEEDRESTART_MODE=a để tự khởi động lại dịch vụ, không hiện hộp thoại hỏi
export DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a
apt update && apt upgrade -y
apt install -y qemu-guest-agent curl wget git vim net-tools ca-certificates \
  gnupg lsb-release apt-transport-https software-properties-common

systemctl enable --now qemu-guest-agent

# Hostname
hostnamectl set-hostname sonarqube
echo "127.0.1.1 sonarqube sonarqube.hoatranlabs.local" >> /etc/hosts

# Static IP. Ubuntu 24.04 ghi mạng của trình cài vào /etc/netplan/50-cloud-init.yaml (DHCP); để nguyên file đó thì DHCP
# cộng dồn với IP tĩnh, nên tắt phần mạng của cloud-init và xóa file cũ trước khi tạo file mới
ip -br link                                  # xem tên NIC thật: ens18 hoặc enp6s18 (máy q35)
NIC=$(ip -br link | awk '$1!="lo"{print $1; exit}')
echo "NIC = $NIC"
echo 'network: {config: disabled}' > /etc/cloud/cloud.cfg.d/99-disable-network-config.cfg
rm -f /etc/netplan/*.yaml
cat > /etc/netplan/50-sonarqube.yaml << EOF
network:
  version: 2
  ethernets:
    ${NIC}:
      addresses: [10.11.65.66/24]
      routes:
        - to: default
          via: 10.11.65.1
      nameservers:
        addresses: [10.11.45.53]
        search: [hoatranlabs.local]
EOF
chmod 600 /etc/netplan/50-sonarqube.yaml
netplan apply
# Phiên SSH sẽ đứt vì IP đổi từ DHCP sang 10.11.65.66: đăng nhập lại bằng IP mới (sudo -i) rồi chạy tiếp từ phần sysctl bên dưới

# SonarQube yêu cầu vm.max_map_count >= 524288 và fs.file-max >= 131072 (docs SonarSource, mục Linux requirements).
# Xem giá trị mặc định của kernel 6.8 trước: nếu fs.file-max đã lớn hơn 131072 thì bỏ dòng fs.file-max bên dưới,
# vì đặt 131072 sẽ HẠ giới hạn toàn hệ thống (cần kiểm lại trên máy thật)
sysctl vm.max_map_count fs.file-max
cat >> /etc/sysctl.d/99-sonarqube.conf << 'EOF'
vm.max_map_count=524288
fs.file-max=131072
EOF
sysctl --system
sysctl vm.max_map_count fs.file-max

# Tăng ulimit cho process
cat >> /etc/security/limits.d/sonarqube.conf << 'EOF'
sonarqube   -   nofile   131072
sonarqube   -   nproc    8192
EOF

# Verify
ip -br -4 addr
ufw status                                   # Ubuntu 24.04: kỳ vọng Status: inactive (firewall do FortiGate đảm nhiệm)
stat -fc %T /sys/fs/cgroup                   # kỳ vọng: cgroup2fs (cgroup v2)
grep SECCOMP /boot/config-$(uname -r)        # Elasticsearch của SonarQube cần CONFIG_SECCOMP=y và CONFIG_SECCOMP_FILTER=y
02

Cài đặt SonarQube

Cài Docker Engine · Tạo cấu trúc thư mục · Docker Compose

2.1 Cài Docker Engine

# Gỡ gói xung đột nếu có (VM mới cài thường chưa có): docker.io, docker-compose, docker-compose-v2, docker-doc, docker-buildx, podman-docker, containerd, runc
apt remove -y $(dpkg --get-selections docker.io docker-compose docker-compose-v2 docker-doc docker-buildx podman-docker containerd runc 2>/dev/null | cut -f1) || true

# Kho chính thức của Docker cho Ubuntu 24.04 (noble), khai báo kiểu deb822 với Signed-By (docs.docker.com/engine/install/ubuntu)
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
cat > /etc/apt/sources.list.d/docker.sources << 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
usermod -aG docker sysadmin

# Verify (bản đã kiểm trong kho noble ngày 2026-10-15: Docker Engine 29.9.1)
docker --version
docker compose version

2.2 Tạo cấu trúc thư mục

mkdir -p /opt/sonarqube/{data,logs,extensions,conf}
mkdir -p /opt/postgresql/{data}

# Tạo user sonarqube
useradd -r -s /bin/false sonarqube || true
chown -R 1000:1000 /opt/sonarqube
chown -R 999:999 /opt/postgresql

2.3 Docker Compose

cat > /opt/sonarqube/docker-compose.yml << 'EOF'
# Không khai báo khóa "version": Docker Compose plugin hiện hành coi khóa này là lỗi thời và in cảnh báo
services:
  postgresql:
    image: postgres:15-alpine
    container_name: sonarqube-db
    restart: unless-stopped
    environment:
      POSTGRES_USER: sonar
      POSTGRES_PASSWORD: "Hoatran@2024!"
      POSTGRES_DB: sonarqube
    volumes:
      - /opt/postgresql/data:/var/lib/postgresql/data
    networks:
      - sonarnet
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U sonar -d sonarqube"]
      interval: 10s
      timeout: 5s
      retries: 5

  sonarqube:
    # Ghim tag đầy đủ của Community Build (phát hành hằng tháng) để cài lại cho kết quả giống nhau;
    # không dùng lts-community (= 9.9.8 cũ). Khớp PostgreSQL 15 (26.x hỗ trợ 15–18) và các lệnh API/SAML trong bài
    image: sonarqube:26.10.0.133078-community
    container_name: sonarqube
    restart: unless-stopped
    depends_on:
      postgresql:
        condition: service_healthy
    environment:
      SONAR_JDBC_URL: jdbc:postgresql://postgresql:5432/sonarqube
      SONAR_JDBC_USERNAME: sonar
      SONAR_JDBC_PASSWORD: "Hoatran@2024!"
      SONAR_WEB_HOST: 0.0.0.0
      SONAR_WEB_PORT: 9000
      SONAR_WEB_CONTEXT: /
      SONAR_LOG_LEVEL: INFO
      SONAR_SEARCH_JAVAADDITIONALOPTS: "-Dnode.store.allow_mmap=false"
      # Passcode cho endpoint giám sát tích hợp /api/monitoring/metrics (gửi trong header X-Sonar-Passcode);
      # Prometheus VM235 dùng đúng chuỗi này ở mục 4.2. Đổi thành chuỗi ngẫu nhiên dài khi dùng thật
      SONAR_WEB_SYSTEMPASSCODE: "Sonar@Passcode2024!"
    volumes:
      - /opt/sonarqube/data:/opt/sonarqube/data
      - /opt/sonarqube/logs:/opt/sonarqube/logs
      - /opt/sonarqube/extensions:/opt/sonarqube/extensions
      - /opt/sonarqube/conf:/opt/sonarqube/conf
    ulimits:
      nofile:
        soft: 131072
        hard: 131072
      nproc:
        soft: 8192
        hard: 8192
    ports:
      - "127.0.0.1:9000:9000"
    networks:
      - sonarnet
    healthcheck:
      test: ["CMD-SHELL", "curl -sf http://localhost:9000/api/system/status | grep -q 'UP'"]
      interval: 30s
      timeout: 10s
      retries: 10
      start_period: 120s

networks:
  sonarnet:
    driver: bridge
EOF

# Khởi động
cd /opt/sonarqube
docker compose up -d

# Theo dõi khởi động (mất khoảng 2-3 phút lần đầu)
docker compose logs -f sonarqube
# Chờ dòng: SonarQube is operational
Terminal sonarqube: docker compose logs -f sonarqube kết thúc bằng dòng 'SonarQube is operational' sau 2-3 phút khởi động lần đầu.
Terminal sonarqube: docker compose logs -f sonarqube kết thúc bằng dòng 'SonarQube is operational' sau 2-3 phút khởi động lần đầu.

2.4 Cài Nginx Reverse Proxy

apt install -y nginx        # Ubuntu 24.04: nginx 1.24, vẫn dùng sites-available / sites-enabled

cat > /etc/nginx/sites-available/sonarqube << 'EOF'
server {
    listen 80;
    server_name sonarqube.hoatranlabs.local;
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl;
    server_name sonarqube.hoatranlabs.local;

    ssl_certificate     /etc/ssl/certs/sonarqube.crt;
    ssl_certificate_key /etc/ssl/private/sonarqube.key;
    ssl_protocols       TLSv1.2 TLSv1.3;
    ssl_ciphers         ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384;
    ssl_prefer_server_ciphers off;

    client_max_body_size 32m;

    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 300;
        proxy_connect_timeout 300;
    }
}
EOF

ln -s /etc/nginx/sites-available/sonarqube /etc/nginx/sites-enabled/
rm -f /etc/nginx/sites-enabled/default

# Chưa chạy `nginx -t` ở bước này: vhost trên trỏ tới cert /etc/ssl/certs/sonarqube.crt
# và key /etc/ssl/private/sonarqube.key, hai file này chỉ được cấp ở mục 3.1 (step-CA).
# `nginx -t` và việc nạp vhost sẽ thực hiện ở cuối mục 3.1, sau khi đã có cert.
03

Cấu hình

Lấy TLS Certificate từ step-CA · Cấu hình ban đầu qua Web UI · Bật endpoint metrics cho Prometheus

3.1 Lấy TLS Certificate từ step-CA

# Cài step CLI 0.31.0 (giá trị dùng chung của lab) bằng gói .deb cho Ubuntu 24.04, như bài 13 (binary /usr/bin/step)
STEP_VERSION="0.31.0"
cd /tmp
wget "https://github.com/smallstep/cli/releases/download/v${STEP_VERSION}/step-cli_${STEP_VERSION}-1_amd64.deb"
apt install -y "./step-cli_${STEP_VERSION}-1_amd64.deb"
step version

# Bootstrap trust với step-CA
step ca bootstrap \
  --ca-url https://step-ca.hoatranlabs.local:9000 \
  --fingerprint [FINGERPRINT_TU_VM242] \
  --install

# Lưu Root CA ở đường dẫn dùng chung của lab (như bài 13, 21, 22) để lệnh bên dưới dùng --root
# (nếu VM đã chạy distribute-root-ca.sh ở bài 13 thì file này đã có sẵn)
step ca root /usr/local/share/ca-certificates/hoatranlabs-root.crt
update-ca-certificates

# Request certificate
step ca certificate sonarqube.hoatranlabs.local \
  /etc/ssl/certs/sonarqube.crt \
  /etc/ssl/private/sonarqube.key \
  --ca-url https://step-ca.hoatranlabs.local:9000 \
  --root /usr/local/share/ca-certificates/hoatranlabs-root.crt \
  --not-after 2160h    # 90 ngày (tối đa theo maxTLSCertDuration của step-CA, bài 13)

# Kiểm tra cấu hình Nginx (lúc này cert đã có) và nạp vhost sonarqube
# (Nginx đã được apt khởi động ở mục 2.4 với cấu hình mặc định nên cần restart)
nginx -t && systemctl enable nginx && systemctl restart nginx

# Tự động renew certificate (cron)
cat > /usr/local/bin/renew-sonarqube-cert.sh << 'CERTEOF'
#!/bin/bash
step ca renew --force \
  /etc/ssl/certs/sonarqube.crt \
  /etc/ssl/private/sonarqube.key
nginx -s reload
CERTEOF
chmod +x /usr/local/bin/renew-sonarqube-cert.sh
echo "0 3 * * 0 root /usr/local/bin/renew-sonarqube-cert.sh >> /var/log/cert-renew.log 2>&1" \
  > /etc/cron.d/sonarqube-cert-renew

3.2 Cấu hình ban đầu qua Web UI

1
Mở https://sonarqube.hoatranlabs.local (cần DNS record sonarqube.hoatranlabs.local → 10.11.65.66 — đã có trong bài 12, xem mục 4.1)
Trình duyệt: trang đăng nhập https://sonarqube.hoatranlabs.local có khóa HTTPS, chứng chỉ CN sonarqube.hoatranlabs.local do step-CA cấp ở mục 3.1.
Trình duyệt: trang đăng nhập https://sonarqube.hoatranlabs.local có khóa HTTPS, chứng chỉ CN sonarqube.hoatranlabs.local do step-CA cấp ở mục 3.1.
2
Login: admin / admin → Đổi password thành Hoatran@2024!
3
Administration → System → Update Center: bật auto-update plugins
4
Administration → Security → Force user authentication: ON
5
Administration → General → Server base URL: https://sonarqube.hoatranlabs.local
SonarQube Administration → General: Server base URL là https://sonarqube.hoatranlabs.local sau khi đã đổi mật khẩu admin.
SonarQube Administration → General: Server base URL là https://sonarqube.hoatranlabs.local sau khi đã đổi mật khẩu admin.

3.3 Bật endpoint metrics cho Prometheus

# SonarQube có sẵn endpoint giám sát
# /api/monitoring/metrics (định dạng Prometheus, có trên Community Build). Endpoint này xác thực bằng passcode
# SONAR_WEB_SYSTEMPASSCODE đã đặt trong docker-compose.yml ở mục 2.3, gửi trong header X-Sonar-Passcode
# (docs SonarSource: endpoint monitoring/metrics không dùng bearer token).
# Kiểm tra (đặt passcode trong nháy đơn để bash không diễn giải dấu !):
curl -s -H 'X-Sonar-Passcode: Sonar@Passcode2024!' \
  https://sonarqube.hoatranlabs.local/api/monitoring/metrics | grep '^sonarqube_health'
# Expected: các dòng sonarqube_health_web_status, sonarqube_health_compute_engine_status,
#           sonarqube_health_elasticsearch_status (giá trị 1 = đang chạy)

3.4 Authentik SAML SSO

# BƯỚC 1: Thông tin Service Provider (SonarQube Community hỗ trợ SAML 2.0, chỉ đăng nhập khởi tạo từ SonarQube;
# cần đặt Server base URL ở mục 3.2 trước). SonarQube không cần file metadata của SP, chỉ cần hai giá trị sau:
#   ACS URL (Assertion Consumer Service): https://sonarqube.hoatranlabs.local/oauth2/callback/saml
#   Application ID (cũng là Audience / SP Entity ID, không có khoảng trắng): sonarqube

# BƯỚC 2: Trên Authentik Web UI
# Providers → Create → SAML Provider:
#   Name: sonarqube-saml
#   ACS URL: https://sonarqube.hoatranlabs.local/oauth2/callback/saml
#   Issuer: https://sonarqube.hoatranlabs.local
#   Service Provider Binding: Post
#   Audience: sonarqube
#   Signing Certificate: authentik Self-signed Certificate
#   Property Mappings: giữ các mapping SAML mặc định của authentik (Email, Name, Username, Groups)
# Sau khi tạo → download IdP metadata XML

# BƯỚC 3: Cấu hình SonarQube SAML
# Administration → Configuration → General Settings → Authentication → SAML → Create Configuration
# Application ID: sonarqube
# Provider Name: Authentik
# Provider ID (Entity ID): từ IdP metadata, field entityID
# SAML login URL: từ IdP metadata, field SingleSignOnService
# Identity provider certificate: từ IdP metadata, field X509Certificate
# Tên attribute là tên mà authentik gửi theo mapping mặc định:
# SAML user login attribute: http://schemas.goauthentik.io/2021/02/saml/username
# SAML user name attribute: http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name
# SAML user email attribute: http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress
# SAML group attribute: http://schemas.xmlsoap.org/claims/Group
# Save configuration → Test Configuration → khi test thành công mới bật Enable (Enabled: ON)
SonarQube Administration → Configuration → General Settings → Authentication → SAML: Application ID sonarqube, Provider Name Authentik, các giá trị lấy từ IdP metadata của Authentik. Test Configuration thành công thì mới bật Enabled.
SonarQube Administration → Configuration → General Settings → Authentication → SAML: Application ID sonarqube, Provider Name Authentik, các giá trị lấy từ IdP metadata của Authentik. Test Configuration thành công thì mới bật Enabled.

3.5 Tích hợp Gitea — Webhook phân tích tự động

Mục này dùng Gitea Actions (workflow .gitea/workflows/sonarqube.yaml chạy scanner mỗi lần push, cần Gitea Runner, trước đây gọi là act_runner, ở bài 22), không dùng webhook của SonarQube. Bản Community chỉ phân tích một nhánh duy nhất là nhánh chính; phân tích nhánh phụ và Pull Request là tính năng từ Developer Edition trở lên, nên workflow chỉ chạy khi push vào main.

# Tạo SonarQube project token cho Gitea
GITEA_SONAR_TOKEN=$(curl -su admin:Hoatran@2024! \
  -X POST "https://sonarqube.hoatranlabs.local/api/user_tokens/generate?name=gitea-ci&type=GLOBAL_ANALYSIS_TOKEN" \
  | python3 -c "import sys,json; print(json.load(sys.stdin)['token'])")

echo "Gitea CI token: $GITEA_SONAR_TOKEN"
# Lưu token này vào Gitea Secret (xem hướng dẫn dưới)

Trên mỗi repo Gitea cần phân tích, tạo file .gitea/workflows/sonarqube.yaml:

# .gitea/workflows/sonarqube.yaml
name: SonarQube Analysis

on:
  push:
    branches: [ main ]   # Community chỉ phân tích nhánh chính; không có phân tích Pull Request / nhánh phụ

jobs:
  sonarqube:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0   # Full history cho SonarQube

      # projectKey chỉ gồm chữ, số, - _ . : (không có "/"), còn gitea.repository có dạng owner/repo
      - name: Tạo projectKey hợp lệ
        run: echo "SONAR_PROJECT_KEY=$(echo '${{ gitea.repository }}' | tr '/' '_')" >> "$GITHUB_ENV"

      # Ghim v7.0.0: bản mới nhất còn chạy bằng node20; từ v7.1.0 action dùng node24 (bản mới nhất hiện là v8.3.0) nên cần
      # image job có Node 24. Job chạy trong image docker.gitea.com/runner-images:ubuntu-latest của runner (bài 22); phiên bản Node
      # trong image đó cần kiểm lại trên máy thật trước khi nâng action. Không dùng @master (nhánh thay đổi liên tục)
      - name: SonarQube Scan
        uses: sonarsource/[email protected]
        env:
          SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
          SONAR_HOST_URL: https://sonarqube.hoatranlabs.local
          # Root CA step-CA (PEM): bundle CA của VM240 mount vào job container (bài 22, mục 8.3) giúp git, curl, Node tin cert nội bộ,
          # còn scanner Java dùng truststore riêng nên vẫn cần root CA này. Action nạp biến này vào truststore của scanner
          # (secret tạo ở cuối mục này)
          SONAR_ROOT_CERT: ${{ secrets.SONAR_ROOT_CERT }}
        with:
          args: >
            -Dsonar.projectKey=${{ env.SONAR_PROJECT_KEY }}
            -Dsonar.sources=.
            -Dsonar.qualitygate.wait=true
# Thêm SONAR_TOKEN vào Gitea repo secret:
# Gitea → Repository → Settings → Secrets → Add Secret
# Name: SONAR_TOKEN, Value: <GITEA_SONAR_TOKEN>
#
# Thêm secret thứ hai (cùng chỗ): SONAR_ROOT_CERT. Bundle CA mount vào job container ở bài 22 phục vụ git, curl, Node; scanner Java
# có truststore riêng nên cần truyền root CA qua secret để tin cert step-CA của https://sonarqube.hoatranlabs.local
# (docs SonarSource "TLS certificates on client side"; action sonarqube-scan-action đọc biến SONAR_ROOT_CERT).
# Name: SONAR_ROOT_CERT, Value: toàn bộ nội dung file root CA (cả dòng BEGIN/END CERTIFICATE), lấy bằng:
cat /usr/local/share/ca-certificates/hoatranlabs-root.crt
Gitea → Repository → Settings → Secrets: secret SONAR_TOKEN và SONAR_ROOT_CERT đã được thêm (che phần giá trị) để workflow .gitea/workflows/sonarqube.yaml sử dụng.
Gitea → Repository → Settings → Secrets: secret SONAR_TOKEN và SONAR_ROOT_CERT đã được thêm (che phần giá trị) để workflow .gitea/workflows/sonarqube.yaml sử dụng.

3.6 Quality Gate mặc định

# Tạo Quality Gate nghiêm ngặt. API quality gate nhận tên gate (name / gateName):
# tham số gateId/id đã bị bỏ từ SonarQube 10.0 và response không còn trường id
QG_NAME="Hoatran-QG"
curl -su admin:Hoatran@2024! \
  -X POST "https://sonarqube.hoatranlabs.local/api/qualitygates/create?name=$QG_NAME"

# Thêm điều kiện: không có Blocker/Critical issue mới
curl -su admin:Hoatran@2024! -X POST \
  "https://sonarqube.hoatranlabs.local/api/qualitygates/create_condition?gateName=$QG_NAME&metric=new_blocker_violations&op=GT&error=0"
curl -su admin:Hoatran@2024! -X POST \
  "https://sonarqube.hoatranlabs.local/api/qualitygates/create_condition?gateName=$QG_NAME&metric=new_critical_violations&op=GT&error=0"
curl -su admin:Hoatran@2024! -X POST \
  "https://sonarqube.hoatranlabs.local/api/qualitygates/create_condition?gateName=$QG_NAME&metric=new_coverage&op=LT&error=70"

# Đặt làm Quality Gate mặc định
curl -su admin:Hoatran@2024! -X POST \
  "https://sonarqube.hoatranlabs.local/api/qualitygates/set_as_default?name=$QG_NAME"
SonarQube → Quality Gates: gate Hoatran-QG có ba điều kiện trên New Code (Blocker Issues > 0, Critical Issues > 0, Coverage < 70%) và nhãn Default.
SonarQube → Quality Gates: gate Hoatran-QG có ba điều kiện trên New Code (Blocker Issues > 0, Critical Issues > 0, Coverage < 70%) và nhãn Default.
04

Tích hợp với hạ tầng

Pi-hole DNS · Prometheus Monitoring · PBS Backup

4.1 Pi-hole DNS

# Record này đã có trong bảng VLAN_SRV / script add_dns_records.sh của bài 12.
# Nếu chưa có, thêm trong Pi-hole Admin (http://10.11.45.53/admin) → Settings → Local DNS Records:
sonarqube.hoatranlabs.local → 10.11.65.66

4.2 Prometheus Monitoring

# Thêm job scrape vào Prometheus VM235
# SSH vào VM235: ssh [email protected]
# Thêm job vào cuối file (mục scrape_configs là mục cuối của prometheus.yml ở bài 15)
# Scrape endpoint tích hợp của SonarQube qua Nginx HTTPS (không còn exporter cổng 9122):
# - X-Sonar-Passcode = SONAR_WEB_SYSTEMPASSCODE đặt ở mục 2.3 (http_headers có từ Prometheus 2.55; secrets được ẩn trên trang /config)
# - ca_file là đường dẫn TRONG container Prometheus: compose bài 15 đã mount root CA của host vào /etc/prometheus/certs/hoatranlabs-root.crt
# - FortiGate: mở 10.11.45.35 -> 10.11.65.66 cổng 443/tcp (thay rule 9122/tcp của exporter cũ; hàng tương ứng ở bảng rule của bài 15)
cat >> /opt/prometheus/prometheus.yml << 'EOF'
  - job_name: 'sonarqube'
    metrics_path: /api/monitoring/metrics
    scheme: https
    tls_config:
      ca_file: /etc/prometheus/certs/hoatranlabs-root.crt
    http_headers:
      X-Sonar-Passcode:
        secrets: ['Sonar@Passcode2024!']
    static_configs:
      - targets: ['sonarqube.hoatranlabs.local:443']
EOF
curl -X POST http://10.11.45.35:9090/-/reload
Prometheus VM235 → Status → Targets: job sonarqube với endpoint https://sonarqube.hoatranlabs.local/api/monitoring/metrics ở trạng thái UP.
Prometheus VM235 → Status → Targets: job sonarqube với endpoint https://sonarqube.hoatranlabs.local/api/monitoring/metrics ở trạng thái UP.

4.3 PBS Backup

# Cài proxmox-backup-client
# Kho client-only công khai là download.proxmox.com, suite trixie (cùng dòng 4.x với PBS của bài 04), khai báo kiểu deb822 với Signed-By;
# khóa đặt trong /usr/share/keyrings (không dùng apt-key). Gói proxmox-backup-client-static là bản liên kết tĩnh (chỉ phụ thuộc qrencode)
# nên không phụ thuộc glibc/thư viện của Ubuntu 24.04; lệnh sử dụng vẫn là proxmox-backup-client. Chạy trên noble: cần kiểm lại trên máy thật.
wget https://enterprise.proxmox.com/debian/proxmox-archive-keyring-trixie.gpg \
  -O /usr/share/keyrings/proxmox-archive-keyring.gpg
cat > /etc/apt/sources.list.d/pbs-client.sources << 'EOF'
Types: deb
URIs: http://download.proxmox.com/debian/pbs-client
Suites: trixie
Components: main
Signed-By: /usr/share/keyrings/proxmox-archive-keyring.gpg
EOF
apt update && apt install -y proxmox-backup-client-static
proxmox-backup-client version

# Script backup
cat > /usr/local/bin/sonarqube-backup.sh << 'EOF'
#!/bin/bash
set -e
cd /opt/sonarqube
docker compose stop sonarqube

# Backup file-level từ trong VM: API token vm-backup@pbs!sonarqube + namespace vm-sonarqube
# (tạo theo bài 04, mục 5.7); PBS_PASSWORD là secret của token đó
export PBS_PASSWORD="<TOKEN_SECRET>"
proxmox-backup-client backup \
  "sonarqube-data.pxar:/opt/sonarqube" \
  "postgresql-data.pxar:/opt/postgresql" \
  --repository "vm-backup@[email protected]:syno-primary" \
  --ns vm-sonarqube

docker compose start sonarqube
EOF
chmod +x /usr/local/bin/sonarqube-backup.sh

echo "0 3 * * * root /usr/local/bin/sonarqube-backup.sh >> /var/log/sonarqube-backup.log 2>&1" \
  > /etc/cron.d/sonarqube-backup
PBS Web UI → Datastore syno-primary → Content → namespace vm-sonarqube: snapshot host/sonarqube có sonarqube-data.pxar và postgresql-data.pxar sau lần chạy sonarqube-backup.sh đầu tiên.
PBS Web UI → Datastore syno-primary → Content → namespace vm-sonarqube: snapshot host/sonarqube có sonarqube-data.pxar và postgresql-data.pxar sau lần chạy sonarqube-backup.sh đầu tiên.
05

Kiểm tra & Xác minh

# 1. Kiểm tra containers
cd /opt/sonarqube
docker compose ps
# Expected: sonarqube-db (healthy), sonarqube (healthy)

# 2. Kiểm tra SonarQube API
curl -su admin:Hoatran@2024! \
  https://sonarqube.hoatranlabs.local/api/system/status
# Expected: {"id":"...","version":"...","status":"UP"}

# 3. Kiểm tra TLS certificate
echo | openssl s_client -connect sonarqube.hoatranlabs.local:443 \
  -servername sonarqube.hoatranlabs.local 2>/dev/null \
  | openssl x509 -noout -subject -dates
# Expected: CN=sonarqube.hoatranlabs.local, notAfter > hôm nay

# 4. Kiểm tra endpoint metrics tích hợp (Prometheus: Status → Targets, job sonarqube phải UP)
curl -s -H 'X-Sonar-Passcode: Sonar@Passcode2024!' \
  https://sonarqube.hoatranlabs.local/api/monitoring/metrics | head -20
# Expected: các metrics sonarqube_* (sonarqube_health_*, sonarqube_web_uptime_minutes, ...)

# 5. Test pipeline: push code lên repo Gitea có file sonarqube.yaml
# Theo dõi: https://sonarqube.hoatranlabs.local → Projects
# Expected: project xuất hiện và có Quality Gate result

# 6. Test SAML login
# Mở browser: https://sonarqube.hoatranlabs.local
# Click "Log in with Authentik" → đăng nhập
# Expected: vào được dashboard với đúng role

# 7. Kiểm tra PostgreSQL
docker exec sonarqube-db psql -U sonar -d sonarqube -c "\dt" | head -20
# Expected: danh sách tables SonarQube
SonarQube → Projects: project của repo Gitea (key dạng <owner>_<repo>, nhánh main) xuất hiện cùng kết quả Quality Gate (Passed/Failed) sau lần push chạy workflow.
SonarQube → Projects: project của repo Gitea (key dạng <owner>_<repo>, nhánh main) xuất hiện cùng kết quả Quality Gate (Passed/Failed) sau lần push chạy workflow.
06

Troubleshooting

Vấn đềNguyên nhânGiải pháp
SonarQube không start, lỗi bootstrap checksvm.max_map_count < 524288 (hoặc fs.file-max < 131072)sysctl vm.max_map_count=524288 và kiểm tra /etc/sysctl.d/99-sonarqube.conf; xem sysctl fs.file-max
DB connection refusedPostgreSQL chưa healthy khi SonarQube startdocker compose logs sonarqube-db → chờ ready to accept connections
Nginx 502 Bad GatewaySonarQube chưa khởi động xongChờ 2-3 phút, kiểm tra docker compose logs sonarqube
SAML login failedEntity ID hoặc ACS URL không khớpSo sánh setting trong SonarQube với Authentik Provider config
Gitea Actions scan failedSONAR_TOKEN sai hoặc hết hạnRegenerate token, cập nhật Gitea secret
Scanner báo lỗi chứng chỉ (PKIX path building failed / unable to find valid certification path)Truststore Java của scanner chưa có root CA step-CAThêm secret SONAR_ROOT_CERT (PEM root CA) và SONAR_ROOT_CERT: ${{ secrets.SONAR_ROOT_CERT }} vào env của bước scan (mục 3.5)
Prometheus target sonarqube báo 401/403Passcode trong prometheus.yml khác SONAR_WEB_SYSTEMPASSCODE, hoặc container sonarqube chưa được tạo lại sau khi thêm biếndocker compose up -d sonarqube, so sánh hai chuỗi, thử lại bằng lệnh curl ở mục 3.3
Quality Gate luôn Pass dù có lỗiqualitygate.wait=true chưa setThêm -Dsonar.qualitygate.wait=true vào scan args
Disk đầy do logsSonarQube log verboseGiảm log level: SONAR_LOG_LEVEL=WARN trong docker-compose

Checklist triển khai

  • VM 266 tạo thành công, qemu-agent chạy
  • Ubuntu 24.04 cài đặt, update, static IP 10.11.65.66 hoạt động (một file netplan duy nhất, cloud-init không ghi đè mạng)
  • vm.max_map_count=524288 đã set và persistent
  • Docker Engine (kho docker.sources suite noble) và Docker Compose Plugin cài thành công
  • Container sonarqube-db healthy, sonarqube healthy
  • TLS certificate từ step-CA cài vào Nginx, HTTPS hoạt động
  • DNS record sonarqube.hoatranlabs.local trong Pi-hole
  • Web UI accessible: https://sonarqube.hoatranlabs.local
  • Admin password đã đổi, Server base URL đã cấu hình
  • Endpoint metrics tích hợp /api/monitoring/metrics trả dữ liệu khi gửi header X-Sonar-Passcode (không còn exporter, cổng 9122 đã bỏ)
  • Prometheus job scrape thêm vào VM235
  • Authentik SAML SSO: đăng nhập thành công qua browser
  • Gitea Actions: push code lên main → SonarQube tự động phân tích
  • Quality Gate Hoatran-QG đặt làm default
  • PBS backup lần đầu thành công
  • Cert auto-renew cron đã cài
Zalo