What is SonarQube and how do you integrate it into a pipeline?
Short answer
SonarQube analyses source code for bugs, security vulnerabilities, code smells, duplicated code and test coverage. You run a scanner in the pipeline that sends results to the SonarQube server, and a quality gate decides pass or fail — if the code doesn't meet the rules, the pipeline stops.
What it checks
| Category | Example |
|---|---|
| Bugs | A variable that can be null used without a check |
| Vulnerabilities | SQL built by joining user input (SQL injection) |
| Security hotspots | Code that needs a human review, like weak cryptography |
| Code smells | Very long methods, duplicated code — hard to maintain |
| Coverage | How much of the code is tested (from JaCoCo, Jest and similar reports) |
Step by step
1. Run SonarQube (for learning):
docker run -d --name sonarqube -p 9000:9000 sonarqube:lts-community
# open http://localhost:9000 (first login admin/admin, then change the password)
# create a project and generate a token
2. Scan the code:
# Maven project
mvn clean verify sonar:sonar \
-Dsonar.projectKey=orders-service \
-Dsonar.host.url=http://sonarqube:9000 \
-Dsonar.token=$SONAR_TOKEN
# Any language, with the CLI scanner
sonar-scanner \
-Dsonar.projectKey=orders-api \
-Dsonar.sources=. \
-Dsonar.host.url=http://sonarqube:9000 \
-Dsonar.token=$SONAR_TOKEN
3. Enforce the quality gate in Jenkins:
stage('SonarQube Analysis') {
steps {
withSonarQubeEnv('sonar-server') {
sh 'mvn -B clean verify sonar:sonar -Dsonar.projectKey=orders-service'
}
}
}
stage('Quality Gate') {
steps {
timeout(time: 5, unit: 'MINUTES') {
waitForQualityGate abortPipeline: true // fail the build if the gate fails
}
}
}
What is a quality gate?
A set of conditions the code must meet, for example: no new critical vulnerabilities, coverage on new code ≥ 80%, duplication on new code ≤ 3%. Teams usually apply the gate to new code, so old projects can still ship while every change makes things better.
What to say in the interview
"SonarQube does static analysis for bugs, vulnerabilities, code smells, duplication and coverage. In our pipeline, after the build and unit tests, we run the Sonar scanner with a token stored in Jenkins credentials. Then the Quality Gate stage waits for SonarQube's result through a webhook and aborts the pipeline if the gate fails — for example new critical issues or coverage below 80% on new code."
Follow-up questions you may get
- Why does
waitForQualityGatehang? The SonarQube webhook back to Jenkins isn't configured or can't reach Jenkins. - SonarQube vs SonarCloud? SonarCloud is the hosted SaaS version; SonarQube is self-hosted.