VPS Tutorials
SonarQube Community on a VPS: CI gates and recoverable backups
Deploy Community Build 26.11 with PostgreSQL and Caddy. Meet host limits, scope CI tokens, enforce failing Quality Gates, back up the real plugin volume, and test database recovery.

SonarQube centralizes static analysis, but a usable service also needs adequate Elasticsearch host limits, PostgreSQL, HTTPS, access controls, CI feedback and recoverable backups. The acceptance target is a real scan whose failed Quality Gate stops the pipeline—not merely an accessible login page.
The original deployment pins Community Build 26.9.0.129388-community. The official Community and Docker releases checked on November 16, 2026 provide 26.11.0.134175; the Docker release was published November 6. For a fresh deployment, use its explicit community image as shown below. Community Build releases monthly: avoid floating latest or community tags, and distinguish it from commercially licensed SonarQube Server versions.
- Review static quality before merging or releasing, within the edition's capabilities.
- Share a Quality Gate across Jenkins, GitHub Actions or other CI.
- Maintain common rules, quality profiles and analysis history.
- Keep private analysis infrastructure under your control.
- Evaluate reliability, security findings, maintainability, coverage and duplication in new code.
It complements tests, dependency scanning, dynamic security testing and human review. Jenkins automates checks; Harbor stores/scans container artifacts.
| Product | Fit | Benefit | Responsibility |
|---|---|---|---|
| Community Build | Individuals/small teams | Free self-hosted analysis | Host, database, upgrades and recovery |
| Licensed Server | Enterprise governance | Edition-specific branches, integrations and security | Licensing and capacity |
| Cloud | Managed infrastructure | No analysis database to operate | Cloud data handling and product billing |
Confirm supported languages, branches, PR analysis and integrations before purchase/migration. This guide establishes main-branch CI gates; it does not promise that every edition supports the same PR features.
The original small-instance baseline is 2 cores, 4GB and 30GB disk with at least 10% free space. A database on the same VPS needs extra headroom.
| Use | Starting VPS | Assumption |
|---|---|---|
| Few personal repositories | 2 cores, 4GB, 50GB NVMe, 2GB swap | Limited scanning/upgrade headroom |
| Small production team | 4 cores, 8GB, 100GB NVMe | Database and service on one host |
| Frequent multi-team scans | 8 cores, 16GB+, 200GB+ NVMe | Consider an independent database |
Code size, analyzers, concurrent jobs, database latency and disk I/O matter as much as CPU. See VPS sizing. Swap can soften a brief spike; it does not replace RAM.
The logical flow is CI/developer → Caddy HTTPS → SonarQube → private PostgreSQL:
开发者 / CI Runner
│ HTTPS 443
▼
Caddy
│ Docker 内网 HTTP 9000
▼
SonarQube
│ PostgreSQL 5432(仅 Docker 内网)
▼
PostgreSQL 17
In this implementation Caddy runs on the host and connects to loopback, while PostgreSQL remains on Docker networking. Publish only:
22/TCPfor restricted SSH.80/TCPfor ACME/redirects.443/TCPfor public HTTPS used by allowed users/runners.
Keep 5432, 9000 and internal Elasticsearch ports private. SonarQube binds to 127.0.0.1:9000.
Point the example hostname to the intended public IPv4 address; add AAAA only if IPv6 works:
sonar.example.com → VPS 公网 IPv4
dig +short sonar.example.com A
Install basic tools:
sudo apt update
sudo apt install -y ca-certificates curl gnupg openssl jq dnsutils
Install Engine/Compose using the official Ubuntu instructions, then verify:
docker version
docker compose version
Check existing memory/swap before provisioning a swap file:
swapon --show
free -h
The current official Linux requirements checked for Community Build match these limits:
vm.max_map_count >= 524288.fs.file-max >= 131072.- At least 131072 open file descriptors for the process.
- At least 8192 threads.
Inspect:
sysctl vm.max_map_count
sysctl fs.file-max
ulimit -n
ulimit -u
Persist host settings:
sudo tee /etc/sysctl.d/99-sonarqube.conf >/dev/null <<'EOF'
vm.max_map_count=524288
fs.file-max=131072
EOF
sudo sysctl --system
Compose supplies nofile/nproc. Restricted OpenVZ/LXC hosting may prevent changing vm.max_map_count with sysctl; verify capability before buying. Do not disable Elasticsearch bootstrap checks to conceal an incompatible host.
sudo mkdir -p /opt/sonarqube
sudo chown -R "$USER":"$USER" /opt/sonarqube
cd /opt/sonarqube
Set umask 077 before the following fresh-instance password generation. It overwrites .env, so retain existing secrets on an established service:
POSTGRES_PASSWORD="$(openssl rand -base64 36 | tr -d '\n')"
SONAR_JWT_SECRET="$(openssl rand -base64 32 | tr -d '\n')"
printf 'POSTGRES_PASSWORD=%s\nSONAR_JWT_SECRET=%s\n' \
"$POSTGRES_PASSWORD" "$SONAR_JWT_SECRET" > .env
chmod 600 .env
unset POSTGRES_PASSWORD SONAR_JWT_SECRET
Keep encrypted recovery copies with administrator-only access.
Create compose.yaml:
services:
db:
image: postgres:17-alpine
container_name: sonarqube-db
restart: unless-stopped
environment:
POSTGRES_DB: sonarqube
POSTGRES_USER: sonarqube
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?set POSTGRES_PASSWORD in .env}
volumes:
- sonarqube_db:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U sonarqube -d sonarqube"]
interval: 10s
timeout: 5s
retries: 10
start_period: 20s
networks:
- sonarnet
sonarqube:
image: sonarqube:26.9.0.129388-community
container_name: sonarqube-app
restart: unless-stopped
depends_on:
db:
condition: service_healthy
environment:
SONAR_JDBC_URL: jdbc:postgresql://db:5432/sonarqube
SONAR_JDBC_USERNAME: sonarqube
SONAR_JDBC_PASSWORD: ${POSTGRES_PASSWORD:?set POSTGRES_PASSWORD in .env}
SONAR_AUTH_JWTBASE64HS256SECRET: ${SONAR_JWT_SECRET:?set SONAR_JWT_SECRET in .env}
ports:
- "127.0.0.1:9000:9000"
volumes:
- sonarqube_data:/opt/sonarqube/data
- sonarqube_extensions:/opt/sonarqube/extensions
- sonarqube_logs:/opt/sonarqube/logs
- sonarqube_temp:/opt/sonarqube/temp
ulimits:
nofile:
soft: 131072
hard: 131072
nproc: 8192
healthcheck:
test: ["CMD-SHELL", "curl --fail --silent http://localhost:9000/api/system/status | grep -q '\"status\":\"UP\"'"]
interval: 30s
timeout: 10s
retries: 20
start_period: 180s
networks:
- sonarnet
networks:
sonarnet:
name: sonarqube-network
volumes:
sonarqube_db:
sonarqube_data:
sonarqube_extensions:
sonarqube_logs:
sonarqube_temp:
For the checked new installation, change only the explicit Community image tag:
cd /opt/sonarqube
sed -i 's/sonarqube:26\.9\.0\.129388-community/sonarqube:26.11.0.134175-community/' compose.yaml
The original documented database range is PostgreSQL 14–18; confirm the chosen Community release's matrix. This example keeps PostgreSQL 17, while its major-version tag still receives patch updates. Pin an approved digest when exact reproducibility is required.
The next configuration command writes expanded secrets to a temporary file. Set umask 077 first, keep the file private and remove it after inspection; prefer docker compose config --quiet for routine checks:
docker compose config >/tmp/sonarqube-compose-rendered.yaml
docker compose pull
docker compose up -d
Startup initializes the database/search indexes:
docker compose ps
docker compose logs -f --tail=200 sonarqube
Expect SonarQube is operational or API UP, then leave log following with Ctrl+C:
curl -fsS http://127.0.0.1:9000/api/system/status | jq
Install Caddy through its official repository if absent. Add the site to /etc/caddy/Caddyfile and ensure its log directory is writable by the Caddy service:
sonar.example.com {
encode zstd gzip
reverse_proxy 127.0.0.1:9000 {
header_up Host {host}
header_up X-Forwarded-Proto {scheme}
header_up X-Forwarded-For {remote_host}
}
log {
output file /var/log/caddy/sonarqube-access.log
format json
}
}
Validate/reload:
sudo caddy validate --config /etc/caddy/Caddyfile
sudo systemctl reload caddy
sudo systemctl status caddy --no-pager
curl -I https://sonar.example.com
curl -fsS https://sonar.example.com/api/system/status | jq
Caddy terminates TLS and forwards Host, X-Forwarded-Proto and X-Forwarded-For. When another trusted proxy/CDN exists, configure that trust explicitly before interpreting original-client addresses. Do not trust arbitrary client-supplied forwarding headers. See Caddy HTTPS.
Open https://sonar.example.com. The initial admin/admin credentials must be changed immediately:
- Save a new administrator password securely.
- Configure base URL through
Administration → Configuration → General → General. - Remove unnecessary anonymous browse/analysis permissions.
- Create an individual Project Analysis Token per CI project.
- Set token expiration and rotation responsibility.
- Avoid administrator User Tokens in CI.
https://sonar.example.com
Tokens are shown fully only at creation. Use Jenkins Credentials/GitHub Secrets; do not store them in sonar-project.properties, Compose or logs.
Create a local project:
Project key: my-api
Display name: My API
Main branch: main
Set sonar-project.properties for actual source/test paths:
sonar.projectKey=my-api
sonar.projectName=My API
sonar.sources=src
sonar.tests=tests
sonar.sourceEncoding=UTF-8
sonar.javascript.lcov.reportPaths=coverage/lcov.info
Run tests that generate the referenced coverage file. Do not add sonar.token to project properties; pass the token through restricted environment:
export SONAR_HOST_URL="https://sonar.example.com"
export SONAR_TOKEN="replace-with-project-analysis-token"
docker run --rm \
-e SONAR_HOST_URL \
-e SONAR_TOKEN \
-v "$PWD:/usr/src" \
sonarsource/sonar-scanner-cli:latest
unset SONAR_TOKEN
The scanner's latest tag is only a demonstration. Pin a reviewed scanner/image in production, and use a credential input method that does not record real tokens in shell history.
Configure Settings → Secrets and variables → Actions:
SONAR_HOST_URL=https://sonar.example.com.SONAR_TOKEN= the project token.
The original .github/workflows/sonarqube.yml workflow is:
name: SonarQube
on:
push:
branches: [main]
pull_request:
jobs:
scan:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Test
run: npm ci && npm test -- --coverage
- name: SonarQube Scan
uses: SonarSource/sonarqube-scan-action@v7
env:
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
SONAR_HOST_URL: ${{ secrets.SONAR_HOST_URL }}
Add this with block to the SonarQube Scan step to make the job wait for the result and fail on a rejected gate:
with:
args: -Dsonar.qualitygate.wait=true
A scan upload alone does not prove a passed gate. For the main-branch Community workflow, remove pull_request until the edition's PR capability is confirmed. Fork PR jobs do not receive repository secrets; do not expose tokens to untrusted code to bypass that boundary.
Hosted runners need reachable HTTPS. For private-only service use a trusted self-hosted runner with proper routes/CA trust. Pin actions to reviewed commit SHAs and align Node/test/coverage settings with the repository.
Install/configure the SonarQube Scanner plugin:
- Add project-token Secret Text under
Manage Jenkins → Credentials. - Configure service URL/credential under
Manage Jenkins → System → SonarQube servers.
Use Jenkinsfile:
pipeline {
agent any
stages {
stage('Test') {
steps {
sh 'npm ci'
sh 'npm test -- --coverage'
}
}
stage('SonarQube Analysis') {
steps {
withSonarQubeEnv('sonarqube-vps') {
sh 'npx sonar-scanner'
}
}
}
stage('Quality Gate') {
steps {
timeout(time: 10, unit: 'MINUTES') {
waitForQualityGate abortPipeline: true
}
}
}
}
}
Provision a reviewed scanner on the agent rather than allowing the unpinned npx sonar-scanner example to download an arbitrary package at runtime. Configure waitForQualityGate callbacks:
https://jenkins.example.com/sonarqube-webhook/
Use a random webhook secret and matching Jenkins secret credential/HMAC verification; where configured per step, set webhookSecretId on waitForQualityGate. Deliberately create a failing gate and verify CI stops. A green-only trial cannot prove enforcement.
Sonar way focuses on new code. Avoid demanding immediate removal of all inherited debt:
- Enforce the gate on New Code first.
- Reject newly introduced high-severity issues.
- Raise coverage targets gradually from a measured baseline.
- Keep duplication limits practical.
- Assign security-hotspot review owners.
- Make a rejected gate fail CI rather than merely notify.
Choose rules the team can explain and reproduce.
sudo ufw allow OpenSSH
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
sudo ufw enable
sudo ufw status numbered
Preserve working SSH access before enabling UFW. Check listeners:
sudo ss -lntp | grep -E ':(443|9000|5432)\b'
9000 should show 127.0.0.1:9000; 5432 should not be published on the host. VPN/identity-proxy restrictions must still allow trusted CI runners to reach the service.
cd /opt/sonarqube
docker compose ps
docker compose logs --tail=200 sonarqube
docker compose logs --tail=200 db
web.log: web, authentication and database.ce.log: background analysis tasks.es.log: Elasticsearch startup/index/disk.access.log: web access where enabled.
docker exec sonarqube-app ls -lh /opt/sonarqube/logs
docker exec sonarqube-app tail -n 100 /opt/sonarqube/logs/web.log
docker exec sonarqube-app tail -n 100 /opt/sonarqube/logs/es.log
Monitor CPU, available RAM, swap, disk/I/O, restarts, database connections and /api/system/status. Alert before Elasticsearch reaches blocking disk watermarks.
PostgreSQL holds authoritative business data; search indexes are rebuildable. Preserve:
- Consistent PostgreSQL dumps.
- Encrypted
compose.yaml/.env. - Plugin list and extensions volume.
- Caddy configuration.
- Exact application/database images.
- Recovery instructions and an actual rehearsal.
Prepare private storage; apply umask 077 and restrictive directory permissions:
sudo mkdir -p /opt/backups/sonarqube
sudo chown -R "$USER":"$USER" /opt/backups/sonarqube
cd /opt/sonarqube
BACKUP_DATE="$(date +%F-%H%M%S)"
docker compose exec -T db \
pg_dump -U sonarqube -d sonarqube -Fc \
> "/opt/backups/sonarqube/sonarqube-${BACKUP_DATE}.dump"
sha256sum "/opt/backups/sonarqube/sonarqube-${BACKUP_DATE}.dump" \
> "/opt/backups/sonarqube/sonarqube-${BACKUP_DATE}.dump.sha256"
The following historical helper uses a logical volume name. Compose normally prefixes it, so substitute the actual existing volume rather than silently backing up a newly created empty one:
docker run --rm \
-v sonarqube_extensions:/source:ro \
-v /opt/backups/sonarqube:/backup \
alpine:3.22 \
tar -czf /backup/sonarqube-extensions.tar.gz -C /source .
tar -czf "/opt/backups/sonarqube/sonarqube-config-${BACKUP_DATE}.tar.gz" \
-C /opt/sonarqube compose.yaml .env
Replace its first helper-container command with:
SONAR_EXTENSIONS_VOLUME="$(docker inspect sonarqube-app --format '{{range .Mounts}}{{if eq .Destination "/opt/sonarqube/extensions"}}{{.Name}}{{end}}{{end}}')"
test -n "$SONAR_EXTENSIONS_VOLUME"
docker volume inspect "$SONAR_EXTENSIONS_VOLUME" >/dev/null
docker run --rm \
--mount "type=volume,src=$SONAR_EXTENSIONS_VOLUME,dst=/source,readonly" \
--mount type=bind,src=/opt/backups/sonarqube,dst=/backup \
alpine:3.22 tar -czf /backup/sonarqube-extensions.tar.gz -C /source .
unset SONAR_EXTENSIONS_VOLUME
Verify dump/archive readability and checksums, preserve Caddy separately, encrypt and upload to independent storage. Rehearse using the backup guide.
Match versions and use a separate host/project with new database volumes and nonconflicting container names/ports. Stop SonarQube on that destination:
cd /opt/sonarqube
docker compose stop sonarqube
These commands replace destination sonarqube; choose the actual saved filename:
docker compose exec -T db dropdb -U sonarqube --if-exists sonarqube
docker compose exec -T db createdb -U sonarqube sonarqube
docker compose exec -T db \
pg_restore -U sonarqube -d sonarqube --clean --if-exists \
< /opt/backups/sonarqube/sonarqube-YYYY-MM-DD-HHMMSS.dump
Restore configuration/plugins, then clear only verified rebuildable Elasticsearch indexes:
docker compose run --rm --entrypoint sh sonarqube \
-c 'rm -rf /opt/sonarqube/data/es8/*'
docker compose up -d
docker compose logs -f --tail=200 sonarqube
The es8 directory is the historical image's index path; verify it for the chosen image before deleting. Never replace this with a broad data-volume wipe. Validate login, projects/history, token scope, a new scan and CI gate feedback.
Do not let Watchtower automatically replace a production image:
- Read intervening release/upgrade notes.
- Check database/plugin/resource compatibility.
- Reserve migration disk headroom; the original planning target is roughly 50% free database-volume space.
- Dump and verify the database.
- Upgrade a restored test copy.
- Change the explicit image tag.
- Pull/start the selected image.
- Check scan, gate, webhook, login and projects.
- Retain old images and pre-upgrade data through observation.
cd /opt/sonarqube
docker compose pull sonarqube
docker compose up -d sonarqube
docker compose logs -f --tail=200 sonarqube
An incompatible database migration requires the old database backup as well as the old application image for rollback.
max virtual memory areas vm.max_map_count is too low
sysctl vm.max_map_count
sudo sysctl -w vm.max_map_count=524288
sudo sysctl --system
Check persistence after reboot and hosting permissions.
docker inspect sonarqube-app --format '{{.State.Status}} {{.State.ExitCode}} {{.State.OOMKilled}}'
docker compose logs --tail=300 sonarqube
free -h
dmesg -T | grep -i -E 'out of memory|killed process' | tail -n 30
Look for RAM, host limits, database readiness, volume permissions or plugin incompatibility.
docker compose ps db
docker compose logs --tail=200 db
docker compose exec db pg_isready -U sonarqube -d sonarqube
Check .env and private rendering with docker compose config. Keep 5432 unpublished.
curl -v https://sonar.example.com/api/system/status
curl -I https://sonar.example.com/batch/index
Test from the runner: DNS, full certificate chain, outbound proxy, firewall and logs. An internal CA needs correct scanner/JVM trust configuration.
- Keep webhook URL ending in
/sonarqube-webhook/. - Check SonarQube can reach Jenkins.
- Check forwarded host/TLS handling.
- Inspect webhook delivery status/body and Jenkins access logs.
- Check plugin/application compatibility.
Do not blindly extend waitForQualityGate timeouts.
df -h
docker system df
docker exec sonarqube-app du -sh /opt/sonarqube/data /opt/sonarqube/logs /opt/sonarqube/extensions
docker exec sonarqube-db du -sh /var/lib/postgresql/data
Locate history, database, logs, plugins and images. Use supported retention and backup/capacity planning instead of arbitrary volume deletion.
- Validate DNS/HTTPS.
- Check
vm.max_map_count,fs.file-max,nofileandnproc. - Pin application/database versions.
- Keep PostgreSQL internal and SonarQube loopback-only.
- Change administrator credentials and public base URL.
- Use project tokens with expiry/rotation.
- Complete a real scan.
- Confirm an intentionally failed gate blocks CI.
- Configure and verify webhook HMAC.
- Test off-host database recovery and actual plugin-volume backup.
- Alert on disk, memory, health and restarts.
- Upgrade through a controlled version/backup process.
For a few low-frequency repositories, with limited headroom. Small teams should consider 4 cores/8GB/100GB NVMe and measure OOM/I/O behavior.
It is for testing. Use a database supported by the selected Community release; this example uses PostgreSQL 17 and the original 14–18 support matrix.
No: use 127.0.0.1:9000 behind Caddy HTTPS.
Check the exact version/product feature matrix. Main-branch scan/gate enforcement works independently of a promise of commercial PR/branch features.
No. PostgreSQL, configuration, stable secrets and plugins need consistent backup and isolated recovery; search indexes can be regenerated.
Keep pinned images and rehearse database/plugin changes. docker compose up -d starting successfully does not establish a safe rollback or working CI integration.