Testing / SonarQube Interview questions
Last updated
1. What is SonarQube?
SonarQube is a self-hosted platform for continuous code inspection. It runs static analysis on source code and reports bugs, vulnerabilities, security hotspots, code smells, duplication and test coverage in a web dashboard.
A scanner runs in the IDE or CI pipeline and uploads its results to the server. The server then compares them with a quality gate that decides whether the code is fit to merge or release.
It is built by Sonar (SonarSource) and covers 30+ languages, such as Java, C#, JavaScript, TypeScript and Python, depending on the edition.
Take quiz
source code, without executing it (static analysis)
only runtime memory dumps from production servers
only network traffic between microservices
the scanner log level
the quality gate
the database vendor
2. What are the editions of SonarQube?
SonarQube Server comes in four self-hosted editions, plus a SaaS option. Each edition adds capabilities on top of the previous one.
| Edition | What it adds |
| Community Build | Free and open source. Analyzes the main branch only, with core languages. |
| Developer | Branch and pull request analysis, PR decoration, deeper security (taint) analysis, extra languages such as C and C++. |
| Enterprise | Portfolio management, security reports, and more languages for legacy stacks. |
| Data Center | Clustered, highly available deployment that scales horizontally. |
SonarQube Cloud (formerly SonarCloud) is the hosted alternative, so there is no server to maintain.
Take quiz
Community Build
Developer Edition
Data Center Edition
the main branch only
every feature branch and pull request
only the test files
3. What are the main components of SonarQube?
A SonarQube Server instance is made of three processes plus a database. Scanners run separately, on the developer machine or build agent.
- Web server - serves the UI and the Web API.
- Search server - an embedded Elasticsearch that indexes issues and projects so searches stay fast.
- Compute Engine - picks uploaded analysis reports off a queue and processes them.
- Database - stores measures, issues, configuration and history.
Each part can be a bottleneck on its own: slow disks hurt Elasticsearch, a small database hurts the Compute Engine, and a busy web server slows the UI. That is why Data Center Edition separates them across nodes.
Take quiz
the Compute Engine
the embedded Elasticsearch search server
the scanner running in CI
the developer's browser
the Git server
the Compute Engine
4. What is SonarScanner?
SonarScanner is the client that analyzes your code and sends the report to SonarQube. The server never pulls code itself, so every analysis starts from a scanner.
There are different flavors for different build tools: the generic SonarScanner CLI, sonar-maven-plugin (mvn sonar:sonar), the org.sonarqube Gradle plugin, and SonarScanner for .NET (begin / build / end steps).
Whichever flavor you use, it needs three things: the server URL, a token, and a project key. The scanner reads the code locally, applies the quality profile it downloaded from the server, and packages findings, measures and coverage into a single report.
Take quiz
SonarScanner for .NET with begin, build and end steps
SonarScanner for Ant only
the Jenkins Blue Ocean plugin
restarts the Elasticsearch process
uploads an analysis report to the SonarQube server
deletes older projects automatically
5. What is a Quality Gate in SonarQube?
A quality gate is a set of conditions on metrics that a project must meet. After each analysis the project gets a simple status: Passed or Failed.
A typical condition looks like "coverage on new code is at least 80%" or "no new bugs". Gates are usually applied to new code, so old problems do not block fresh work.
CI pipelines read this status and stop the build or the deployment when the gate fails.
Each project is attached to exactly one gate at a time. You can see which conditions failed on the project dashboard, which makes the failure easy to act on.
Take quiz
a list of compiler errors
a generated deployment script
a pass or fail status based on its conditions
new code
only the oldest code in the repository
only commit messages
6. What is a Quality Profile in SonarQube?
A quality profile is the set of rules activated for one language. It decides what the scanner looks for when it analyzes Java, Python, JavaScript and so on.
Every language starts with the built-in Sonar way profile. Built-in profiles are read-only, so to change rules you copy or extend one, then assign the new profile to a project or make it the default.
Because profiles are per language, a Java and TypeScript project can use two different profiles at once. Rule changes take effect on the next analysis, not retroactively on old results.
Take quiz
a list of user permissions
a set of activated rules for one language
a schedule for database backups
edit the built-in profile directly
delete the Elasticsearch index
copy or extend it and edit the copy
7. What are the types of issues SonarQube reports?
Classically SonarQube groups findings into three types:
| Bug | Vulnerability | Code Smell |
| Code that is wrong and can break at runtime, such as a null dereference. | A security weakness an attacker could exploit, such as SQL injection. | Code that works but is hard to read or change, such as a huge method. |
| Affects reliability. | Affects security. | Affects maintainability. |
Newer versions also describe each issue by Clean Code attribute and software quality (Security, Reliability, Maintainability) with an impact level, but the three classic types are still widely used.
Take quiz
Bug
Code Smell
Security Hotspot
network latency
maintainability
software licensing
8. What is a Security Hotspot in SonarQube?
A security hotspot is a piece of security-sensitive code that needs a human to decide whether it is actually a problem. SonarQube cannot prove it is exploitable, so it asks for a review.
Common examples are weak hashing algorithms, permissive CORS settings, and regular expressions that may cause denial of service.
A reviewer sets the status to Safe if there is no real risk, or Fixed after changing the code. Unreviewed hotspots usually count against the quality gate.
Reviewing hotspots needs the Administer Security Hotspots permission on the project, and each review is recorded with a comment so the decision stays auditable.
Take quiz
nothing, it is ignored automatically
immediate deletion of the file
a manual review to decide whether the code is safe
you judged the code poses no real risk
the file was excluded from the build
the hotspot became a bug
9. What is technical debt in SonarQube?
Technical debt is the estimated time needed to fix all maintainability issues (code smells) in a project. SonarQube shows it in minutes, hours or days, where a day is 8 hours.
Each rule carries a remediation estimate, either a fixed amount or one that grows with the size of the problem. SonarQube adds these up to give the total, which feeds the Maintainability rating.
For example, a rule for an overly long method might estimate 20 minutes per occurrence, so 30 occurrences add up to 10 hours. The figure is an estimate to help prioritize, not a promise of actual effort.
Take quiz
as the number of commits
as estimated remediation time
as JVM heap size
network outages
the number of open pull requests
maintainability issues (code smells)
10. What are the Reliability, Security and Maintainability ratings?
SonarQube turns raw numbers into A to E ratings so you can read project health at a glance.
- Reliability - based on the worst open bug. A means no bugs, E means at least one blocker-level bug.
- Security - based on the worst open vulnerability, using the same A to E scale.
- Maintainability - based on the technical debt ratio, where A means 5% or less.
- Security Review - based on the percentage of security hotspots reviewed.
Because ratings come from the worst issue, a single blocker bug drops Reliability to E regardless of how clean the rest is. This makes them a good fit for quality gates, which usually require an A on new code.
Take quiz
Maintainability
Reliability
Security
100% test coverage
no open bugs
zero duplicated lines
11. How does SonarQube measure code coverage?
It does not measure coverage itself. SonarQube never runs your tests; it imports a coverage report produced by another tool, such as JaCoCo, Cobertura, lcov or coverage.py.
You run tests with coverage enabled, point the scanner at the report file with the right property, then run the analysis. SonarQube shows line coverage, condition coverage and the combined figure, for overall and new code.
If the report is missing or the paths do not match, coverage shows no data.
The property name depends on the language and format, for example sonar.coverage.jacoco.xmlReportPaths for JaCoCo or sonar.python.coverage.reportPaths for Python.
Take quiz
SonarQube runs the unit tests itself
the Elasticsearch node
a coverage tool such as JaCoCo, whose report SonarQube imports
coverage shows no data for the project
coverage defaults to 100%
SonarQube estimates coverage from file size
12. How does SonarQube detect duplicated code?
SonarQube compares blocks of tokens across files and flags blocks that repeat. The thresholds depend on the language:
- Java: at least 10 successive duplicated statements, whatever the token or line count.
- Most other languages: at least 100 successive duplicated tokens spread over at least 10 lines.
- COBOL and ABAP: same token count but across more lines (30 and 20).
The key metric is duplicated lines density, the percentage of lines that sit inside duplicated blocks. Use sonar.cpd.exclusions to skip files, for example generated code.
Take quiz
the percentage of failing tests
the percentage of lines inside duplicated blocks
the number of Git branches
sonar.coverage.exclusions
sonar.host.url
sonar.cpd.exclusions
13. What is the sonar-project.properties file?
It is the configuration file the SonarScanner CLI reads from the project root. It tells the scanner what to analyze and where to send the results.
sonar.projectKey=my-org_my-app sonar.projectName=My App sonar.sources=src/main sonar.tests=src/test sonar.sourceEncoding=UTF-8 sonar.host.url=http://localhost:9000
Keep the authentication token out of this file. Pass it through the SONAR_TOKEN environment variable or a CI secret.
Maven and Gradle projects do not need this file because the build plugin supplies the same information. Property values can also be overridden on the command line with -D, which takes precedence over the file.
A multi-module layout can define modules with sonar.modules, each with its own sources path.
Take quiz
sonar.sources
sonar.projectName
sonar.sourceEncoding
committed inside sonar-project.properties
in the SONAR_TOKEN environment variable or a CI secret
written in a code comment
14. Which databases does SonarQube support?
SonarQube Server supports PostgreSQL, Microsoft SQL Server and Oracle. PostgreSQL is the most common choice and the one used in Docker examples.
There is also an embedded H2 database that starts by default, but it is for evaluation only. You cannot migrate its data to a production database, so switch to a supported external database before real use.
MySQL is not supported.
Supported versions change with each release, so check the requirements page for your target version before choosing. Use UTF-8 encoding and a case-sensitive collation where the vendor requires it, and give SonarQube a dedicated schema or database.
Take quiz
PostgreSQL
Microsoft SQL Server
MySQL
evaluation and testing only
production clusters
Data Center Edition nodes
15. What is the Clean as You Code approach?
Clean as You Code means making sure new and changed code meets your quality standards, instead of trying to fix the whole legacy codebase first.
SonarQube supports it through the new code period and quality gates that look only at new code. Teams stop adding debt right away, and old code gets cleaned up gradually as it is touched.
In practice this means the quality gate fails when a pull request adds a new bug or drops coverage, even if the project has thousands of old issues. Developers fix only what they touch, so the overall debt shrinks over time without a dedicated cleanup project.
Take quiz
fixing every legacy issue before any release
making sure new and changed code meets the standard
deleting old branches
tests are no longer required
builds compile faster
teams improve quality without a big upfront legacy cleanup
16. What is the default SonarQube port and how do you change it?
The web server listens on port 9000 by default, so a local install is reachable at http://localhost:9000.
To change it, set sonar.web.port in conf/sonar.properties and restart. You can also set sonar.web.host to bind to one interface, or sonar.web.context to serve under a path such as /sonar. In Docker, just map a different host port with -p.
If you put SonarQube behind a reverse proxy, keep the internal port as is and expose 443 at the proxy. Remember to update sonar.host.url in scanner configs and webhooks after any port or URL change.
Take quiz
9000
8080
3306
sonar-project.properties in the project
sonar.web.port in conf/sonar.properties
pom.xml of each module
17. What is SonarQube for IDE?
SonarQube for IDE, formerly SonarLint, is a plugin for IDEs like VS Code, IntelliJ, Eclipse and Visual Studio. It highlights issues as you type, before you commit.
In standalone mode it uses a default rule set. In connected mode it binds to a SonarQube server and uses that project's quality profile and settings, so the IDE and the server agree.
It supports many languages and also surfaces security hotspots. Connected mode needs a token and the project key, and it can sync suppressed issues so a finding you marked as false positive on the server stays hidden in the IDE.
Take quiz
SonarScanner
SonarCloud
SonarLint
the server's quality profile and project settings
automatic deployment to production
a replacement for the database
18. What is the default Sonar way quality gate?
The built-in Sonar way gate focuses on new code. In current versions its conditions are:
- No new issues.
- All new security hotspots are reviewed (100%).
- Coverage on new code is at least 80%.
- Duplicated lines on new code are at most 3%.
It is read-only. To adjust thresholds, copy it into a custom gate.
Because every condition targets new code, a project with heavy legacy debt can still pass if its latest changes are clean. Older versions of the gate used letter ratings, so check which version you run before quoting thresholds in an interview.
Take quiz
50%
80%
100%
10%
30%
3%
19. How do you generate and use an analysis token in SonarQube?
Open My Account > Security, give the token a name, choose a type and click Generate. Copy it immediately, because it is shown only once.
There are three types: a user token (acts as you), a project analysis token (analysis of one project only) and a global analysis token (analysis of any project). For CI, prefer a project analysis token because a leak has a small blast radius.
Pass it to the scanner with sonar.token (older versions used sonar.login), ideally through SONAR_TOKEN stored as a CI secret.
Take quiz
project analysis token
global analysis token
user token with admin rights
every time you open the profile page
only once, right after creation
never, it is emailed
20. What is the difference between SonarQube Server and SonarQube Cloud?
Both run the same kind of analysis, but they differ in who operates them.
| SonarQube Server | SonarQube Cloud |
| Self-hosted on your own infrastructure. | SaaS hosted by Sonar (formerly SonarCloud). |
| You manage the database, upgrades, backups and scaling. | Sonar manages infrastructure and ships updates continuously. |
| Needed when code or data must stay in your network. | Fastest start for cloud-hosted repositories. |
Pick Server for strict data-residency or air-gapped needs, and Cloud when you want zero server maintenance.
Migrating is possible, but quality gate history does not move automatically, so plan a baseline analysis on the new platform.
Take quiz
your own operations team
the Git provider
Sonar, as a hosted service
SonarQube Server
SonarQube Cloud
neither can run offline
21. How does a SonarQube analysis work end to end?
The scanner does the heavy lifting locally, and the server only processes the finished report.
sequenceDiagram
participant D as Developer / CI
participant S as Scanner
participant W as SonarQube Web Server
participant C as Compute Engine
participant DB as Database + Elasticsearch
D->>S: run analysis
S->>W: fetch quality profiles and settings
S->>S: analyze sources, tests, coverage reports
S->>W: upload analysis report
W->>C: queue background task
C->>DB: store measures and issues, update indexes
C->>C: evaluate quality gate
W-->>D: gate status (API or webhook)
Because processing is asynchronous, a successful scanner run does not yet mean the gate result is ready. CI has to wait for the background task.
Take quiz
inside the database
in the scanner, on the developer machine or build agent
in the browser
the scanner compiles the code later
the database is locked until midnight
the Compute Engine processes the report asynchronously
22. What is the difference between a vulnerability and a security hotspot?
A vulnerability is a confirmed weakness: the analyzer is confident the code can be exploited, and it must be fixed. It affects the Security rating directly.
A security hotspot is only security-sensitive. Whether it is dangerous depends on context, such as who controls the input, so a developer reviews it and marks it Safe or fixes it. Hotspots feed the Security Review rating rather than the Security rating.
Example: building SQL from a request parameter is a vulnerability. Using the MD5 hash function might be a hotspot, because it is fine for a cache key but not for passwords.
Take quiz
a security hotspot
a vulnerability
a code smell
the Reliability rating
the Security Review rating
the Maintainability rating
23. How do you integrate SonarQube with Jenkins?
Install the SonarQube Scanner plugin, then add your server URL and an authentication token under Manage Jenkins > System. Finally, add a webhook in SonarQube pointing to JENKINS_URL/sonarqube-webhook/ so Jenkins gets the gate result.
pipeline { agent any stages { stage('Analysis') { steps { withSonarQubeEnv('sonar-server') { sh 'mvn -B verify sonar:sonar' } } } stage('Quality Gate') { steps { timeout(time: 10, unit: 'MINUTES') { waitForQualityGate abortPipeline: true } } } } }
withSonarQubeEnv injects the URL and token, and waitForQualityGate pauses until the webhook arrives.
Take quiz
withSonarQubeEnv
archiveArtifacts
waitForQualityGate
so SonarQube can notify Jenkins when the analysis finishes
to back up the database
to rotate tokens automatically
24. How do you fail a CI pipeline when the quality gate fails?
The scanner exit code alone does not reflect the gate, because processing happens after the upload. You need one of these approaches:
- Add
sonar.qualitygate.wait=trueso the scanner waits and exits non-zero when the gate fails. Tune the wait withsonar.qualitygate.timeout. - Use the CI-specific helper, such as
waitForQualityGatein Jenkins or the SonarQube quality gate action in GitHub Actions. - Call
api/qualitygates/project_statusyourself and check forOKorERROR.
mvn -B verify sonar:sonar -Dsonar.qualitygate.wait=true
Whichever way you choose, set a timeout so a stuck background task does not hang the pipeline forever. A failed gate should block the merge or deploy, not just print a warning.
Take quiz
sonar.sources=src
sonar.qualitygate.wait=true
sonar.sourceEncoding=UTF-8
api/system/restart
api/users/create
api/qualitygates/project_status
25. How do you import JaCoCo coverage into SonarQube?
Generate an XML report with JaCoCo during the build, then tell the scanner where it is. The tests must run before the scan so the report exists.
mvn clean verify sonar:sonar \ -Dsonar.coverage.jacoco.xmlReportPaths=target/site/jacoco/jacoco.xml
Make sure the JaCoCo Maven plugin has the prepare-agent and report goals bound. Only the XML format is read by SonarQube; the HTML report is for humans. For multi-module builds, list several paths separated by commas, or use a wildcard.
If coverage still shows zero, check that the report paths are correct relative to the project root and that the source files in the report match the scanned files.
Take quiz
XML
HTML
PNG
SonarQube compiles the tests itself
the coverage report has to exist when the scanner starts
JaCoCo only runs after analysis
26. How does pull request analysis work in SonarQube?
Pull request analysis is available from Developer Edition upwards. The scanner analyzes the PR branch and SonarQube compares it with the target branch, so the PR only gets blame for issues it introduces.
- Analyze the target branch first, so there is a baseline.
- Run the scan with
sonar.pullrequest.key,sonar.pullrequest.branchandsonar.pullrequest.base. Many CI integrations detect these automatically. - SonarQube posts a quality gate status and inline comments back to GitHub, GitLab, Bitbucket or Azure DevOps (PR decoration).
- Branch protection can then require the gate to pass before merge.
The Community Build cannot do this, because it analyzes only the main branch.
Take quiz
Community Build only
only the Data Center Edition
Developer Edition and above
the target branch
the oldest tag in the repository
the CI server itself
27. What is the difference between sonar.exclusions and sonar.coverage.exclusions?
| sonar.exclusions | sonar.coverage.exclusions |
| Files are not analyzed at all: no issues, no duplication, no coverage. | Files are still analyzed for issues and duplication, but ignored in coverage calculation. |
| Use for generated code, vendor folders, build output. | Use for code you do not want to unit test, such as configuration classes or DTOs. |
Two related properties exist: sonar.cpd.exclusions skips duplication checks only, and sonar.test.exclusions removes files from the test set. Patterns use Ant-style wildcards, for example **/generated/**.
A common mistake is excluding a folder with sonar.exclusions when you only want to ignore it for coverage, which silently hides real issues in that code.
Take quiz
sonar.exclusions
sonar.coverage.exclusions
sonar.sources
regular expressions only
SQL LIKE patterns
Ant-style wildcard patterns
28. How do you create a custom quality gate in SonarQube?
Go to Quality Gates and either create a new gate or copy Sonar way, since built-in gates are read-only. Copying keeps the sensible defaults and lets you tweak only what you need.
- Add conditions on a metric, such as coverage on new code below 85% or new bugs above 0.
- Prefer conditions on new code to follow Clean as You Code.
- Assign the gate to specific projects, or make it the default for new ones.
- Re-run analysis so the new gate is evaluated.
Requires the Administer Quality Gates permission.
Take quiz
built-in gates are read-only
Sonar way cannot be assigned to any project
copying deletes all old projects
Execute Analysis
Administer Quality Gates
Browse
29. How do you customize a quality profile in SonarQube?
Open Quality Profiles, choose the language and either Copy or Extend the built-in profile. Extending creates a child that inherits every rule from its parent.
In the child you can activate or deactivate rules, change severity, and tune rule parameters such as maximum method length. Any rule not overridden keeps following the parent, so parent updates flow down.
Then set the profile as the default for the language, or assign it to chosen projects. You can compare two profiles to see rule differences, and back up a profile as XML to move it between instances.
Take quiz
deletes the parent profile
turns off all rules for that language
creates a child that inherits the parent's rules
back it up as XML and restore it
email the database
copy the Elasticsearch folder
30. Why does SonarQube use a new code period?
The new code period defines which code counts as new, so quality gates can judge recent work instead of years of history. Without it, a legacy project would fail its gate forever.
You can define it as the previous version, a number of days, a specific analysis or date, or a reference branch. SonarQube works out which lines are new from SCM blame data, so the scanner needs access to Git history (avoid shallow clones).
The default is usually the previous version, and it can be set globally or per project. Branches can follow a reference branch, which suits pull request workflows.
Take quiz
to count test cases
to work out which lines are new
to download plugins
it speeds up the quality gate
it improves coverage
it can hide history, so new code may be detected wrongly
31. How do you import external linter results into SonarQube?
Use sonar.externalIssuesReportPaths with the Generic Issue Data JSON format. Many tools also have a direct property, such as sonar.eslint.reportPaths or sonar.python.pylint.reportPaths.
{ "issues": [ { "engineId": "my-linter", "ruleId": "NO-TODO", "severity": "MINOR", "type": "CODE_SMELL", "primaryLocation": { "message": "Remove this TODO comment", "filePath": "src/App.js", "textRange": { "startLine": 10 } } } ] }
External issues appear on the dashboard but are managed by the original tool, so you cannot change their rules from SonarQube.
Make sure file paths in the report are relative to the project root, or the issues will be dropped silently. Run the linter before the scan so the report file is fresh.
Take quiz
sonar.externalIssuesReportPaths
sonar.coverage.jacoco.xmlReportPaths
sonar.web.port
in the quality gate
in the original linter, not in SonarQube
in the Elasticsearch config
32. How do you reduce false positives in SonarQube?
First check whether the finding is truly a false positive. If it is, you have several options, from narrow to broad:
- Mark the single issue as False positive in the UI, or Accepted when the risk is real but tolerated.
- Add a
// NOSONARcomment to silence that line. It hides every rule on the line, so use it sparingly. - Use
sonar.issue.ignore.multicriteriato ignore a rule for matching files. - Deactivate or tune the rule in the quality profile if it is noisy for your whole codebase.
int x = legacyCall(); // NOSONAR - validated upstream
Report genuine false positives on the Sonar community forum so the rule can be improved.
Take quiz
deletes the file from the project
lowers coverage threshold
suppresses issues on that line
Accepted
Fixed
Reopened
33. What are webhooks in SonarQube and when would you use them?
A webhook is an HTTP POST that SonarQube sends when an analysis finishes. The JSON payload includes the project key, the task status and the quality gate result.
{ "taskId": "AX...", "status": "SUCCESS", "project": { "key": "my-app" }, "qualityGate": { "name": "Sonar way", "status": "OK" } }
Typical uses: unblock Jenkins waitForQualityGate, post to Slack, or gate a deployment. Set a secret and verify the X-Sonar-Webhook-HMAC-SHA256 header so your receiver can trust the call.
Webhooks can be defined globally or for a single project. SonarQube retries nothing, so make the receiver quick and idempotent, and check the delivery log under the webhook settings if a call seems lost.
Take quiz
Content-Length
X-Sonar-Webhook-HMAC-SHA256
X-Forwarded-For
when a user logs in
at every database backup
after analysis processing completes
34. How do you use the SonarQube Web API for automation?
Every UI action is backed by the Web API under /api. Authenticate with a token as the username and an empty password.
# quality gate status curl -u $SONAR_TOKEN: "https://sonar.example.com/api/qualitygates/project_status?projectKey=my-app" # open issues curl -u $SONAR_TOKEN: "https://sonar.example.com/api/issues/search?projects=my-app&resolved=false" # selected measures curl -u $SONAR_TOKEN: "https://sonar.example.com/api/measures/component?component=my-app&metricKeys=coverage,bugs
Use it for dashboards, release checks and bulk admin work such as creating projects. Browse the in-app Web API page for the full, version-specific list.
Responses are JSON and large lists are paged with p and ps, with a hard cap of 10,000 results per search, so narrow filters for big projects.
Take quiz
as the username with an empty password
inside the URL fragment only
as an XML attachment
api/webhooks/create
api/measures/component
api/system/logs
35. How is the technical debt ratio calculated in SonarQube?
Technical debt ratio = remediation cost / development cost. Development cost is estimated as lines of code multiplied by a cost per line, which defaults to 30 minutes (configurable under Administration).
Example: 10,000 lines gives 300,000 minutes, or 5,000 hours of development cost. If remediation is 250 hours, the ratio is 5%.
| Debt ratio | Maintainability rating |
| 0% to 5% | A |
| 5% to 10% | B |
| 10% to 20% | C |
| 20% to 50% | D |
| above 50% | E |
Because the denominator grows with code size, a large project can carry more absolute debt than a small one and still earn an A. Change the cost per line or the rating grid only if your team has a good reason, and apply it consistently.
Take quiz
25%
50%
5%
C
A
E
36. What is the difference between SonarQube and tools like Checkstyle or PMD?
| Checkstyle / PMD | SonarQube |
| Run as build plugins and write a report per build. | Central server that stores history across builds and projects. |
| Focused on style rules or a language's defect patterns. | Covers bugs, vulnerabilities, hotspots, smells, duplication and coverage. |
| No built-in pass/fail policy across teams. | Quality gates give a shared pass/fail policy. |
They are complementary. SonarQube can import Checkstyle or PMD results as external issues, so teams keep existing rules and still get one dashboard.
In an interview, the short version is: Checkstyle and PMD are rule engines, SonarQube is a quality management platform that also contains its own rule engines.
Take quiz
compiled bytecode
history and trends across analyses on a central server
a copy of the JVM
it cannot read them
by running Checkstyle in the browser
import them as external issues
37. What are project permissions and global permissions in SonarQube?
| Global permissions | Project permissions |
| Apply across the whole instance. | Apply to a single project. |
| Administer System, Administer Quality Gates, Administer Quality Profiles, Create Projects, Execute Analysis. | Browse, See Source Code, Administer Issues, Administer Security Hotspots, Execute Analysis, Administer. |
| Usually given to platform administrators. | Usually given to project teams through groups. |
Grant permissions to groups, not individual users, and use permission templates so new projects get consistent access automatically.
Execute Analysis exists at both levels: global lets a token analyze any project, project-level limits it to one. Prefer the narrower one for CI accounts.
Take quiz
Administer Quality Gates
See Source Code
Administer Security Hotspots
the Elasticsearch config
permission templates
scanner properties
38. How do you secure a SonarQube installation?
- Put it behind a reverse proxy such as Nginx with HTTPS.
- Change the default
adminpassword at first login, and keepsonar.forceAuthenticationenabled. - Use SSO (SAML, GitHub, GitLab or LDAP) and map IdP groups to SonarQube groups.
- Use scoped analysis tokens for CI instead of personal passwords.
- Run as a non-root OS user and keep the database on a private network.
- Back up regularly and stay on an active, patched version.
Also restrict who can create tokens and projects, review audit logs where your edition provides them, and rotate tokens when people leave. Treat the SonarQube host like any system holding source code.
Take quiz
they make analysis faster
they replace the database
a leaked token exposes far less than a personal password
a reverse proxy
the Elasticsearch node
the scanner
39. How does SonarQube find injection vulnerabilities using taint analysis?
Taint analysis tracks untrusted data from a source (for example an HTTP parameter) through method calls to a sink (for example a SQL execution). If it arrives without passing a sanitizer, SonarQube reports a vulnerability.
The analysis follows data across methods and files, which is why it finds problems that single-file rules miss. It is available from the Developer Edition upwards.
flowchart LR
A["Source: request parameter"] --> B["Assignments and method calls"]
B --> C{Sanitizer applied?}
C -- Yes --> D["No issue"]
C -- No --> E["Sink: SQL query"]
E --> F["Vulnerability reported"]
String id = request.getParameter("id"); // source String sql = "SELECT * FROM users WHERE id = " + id; // tainted stmt.executeQuery(sql); // sink -> issue
The fix is a PreparedStatement with a bound parameter, which breaks the tainted flow.
Take quiz
the first line of a file
a sensitive operation such as running a SQL query
a Git remote
adding more comments
renaming the variable
a sanitizer or a parameterized query
40. How do you run SonarQube with Docker and PostgreSQL?
Run two containers, SonarQube and PostgreSQL, and persist the data, extensions and logs in volumes so upgrades do not lose state.
services: sonarqube: image: sonarqube:community depends_on: [db] environment: SONAR_JDBC_URL: jdbc:postgresql://db:5432/sonar SONAR_JDBC_USERNAME: sonar SONAR_JDBC_PASSWORD: ${SONAR_DB_PASSWORD} volumes: - sonarqube_data:/opt/sonarqube/data - sonarqube_extensions:/opt/sonarqube/extensions - sonarqube_logs:/opt/sonarqube/logs ports: ["9000:9000"] db: image: postgres:17 environment: POSTGRES_USER: sonar POSTGRES_PASSWORD: ${SONAR_DB_PASSWORD} POSTGRES_DB: sonar volumes: - postgres_data:/var/lib/postgresql/data volumes: sonarqube_data: sonarqube_extensions: sonarqube_logs: postgres_data:
Set vm.max_map_count on the Docker host or Elasticsearch will refuse to start. Use the image tag for your edition and pin versions instead of latest.
Take quiz
so state survives container recreation and upgrades
to make the scanner faster
to disable Elasticsearch
net.ipv4.ip_forward
vm.max_map_count
kernel.hostname
41. How do you troubleshoot SonarQube failing to start with Elasticsearch errors?
Start with logs/es.log and logs/sonar.log. Most startup failures come from Elasticsearch bootstrap checks that run in production mode.
- Kernel and limits:
vm.max_map_countat least 524288 (older versions asked for 262144),fs.file-maxat least 131072, open files limit of 131072 and process limit of 8192. - Running as root: Elasticsearch refuses to start. Use a dedicated user.
- Low disk space: past the watermark, indexes go read-only and startup or indexing fails.
- Unsupported Java or permissions on the
dataandtempfolders.
sudo sysctl -w vm.max_map_count=524288 echo "vm.max_map_count=524288" | sudo tee -a /etc/sysctl.d/99-sonarqube.conf
If the index is corrupt after a crash, stop the server, clear the data/es* folder and restart so it rebuilds from the database.
Take quiz
conf/wrapper.conf
extensions/plugins
logs/es.log
it is a built-in safety check
root has too little memory
the database blocks root
42. How do you upgrade SonarQube safely?
- Read the release and upgrade notes for every version you will cross. Follow the LTA-to-LTA path, and update to the intermediate LTA first if you are too far behind.
- Take a full database backup and copy
conf/,extensions/and custom plugins. - Check that third-party plugins have a version compatible with the target.
- Rehearse the upgrade on a staging copy of the production database.
- Stop the server, install the new version (or pull the new image) with the same config and database, and start it.
- Open
/setupand run the database migration, then wait for it to finish. - Re-run a few analyses and compare results.
Recent versions place newly detected issues from changed rules into a sandbox, so an upgrade does not suddenly fail quality gates. Never run an older version against a migrated database; roll back with the backup.
Take quiz
delete the extensions folder
back up the database and configuration
disable authentication
/api/system/restart
/projects/create
/setup
43. How does SonarQube track issues across analyses?
Each analysis produces a fresh list of findings, and the Compute Engine matches them against the previous list so an issue keeps its identity, status and comments over time.
Matching uses rule key, file, and a hash of the code line and its context, rather than just the line number. If lines move because someone added code above, the issue is still recognized as the same one.
An issue that is no longer found gets Fixed automatically. Manual states such as Accepted or False positive carry forward until the code or rule changes. This is what keeps new-code metrics accurate.
Take quiz
adding code above shifts line numbers
line numbers are encrypted
scanners never read line numbers
Open forever
Fixed
Deleted from the audit log
44. How does the SonarQube Compute Engine process an analysis report?
The Compute Engine (CE) is a background worker that handles each uploaded report as a task in a queue. By default one task runs at a time per CE worker, and higher editions can process several in parallel.
- Read and validate the report.
- Compute measures and ratings for files, directories and the project.
- Track issues against the previous analysis.
- Evaluate the quality gate.
- Persist results to the database and update Elasticsearch indexes.
- Fire webhooks and notifications.
Failed or long-running tasks show under Administration > Projects > Background Tasks, and details are in logs/ce.log. A growing queue is a sign that CE capacity or database performance is the bottleneck.
Take quiz
the My Account page
the sonar-project.properties file
Administration > Projects > Background Tasks
logs/ce.log
logs/access.log
logs/es.log
45. How do you scale SonarQube using Data Center Edition?
Data Center Edition splits the platform into application nodes (web server plus Compute Engine) and search nodes (Elasticsearch cluster), with one shared database and a load balancer in front. A typical layout is at least two application nodes and three search nodes.
flowchart TB
LB["Load balancer"] --> A1["Application node 1"]
LB --> A2["Application node 2"]
A1 --> S1["Search node 1"]
A1 --> S2["Search node 2"]
A1 --> S3["Search node 3"]
A2 --> S1
A2 --> S2
A2 --> S3
A1 --> DB[(Shared database)]
A2 --> DB
This removes the single point of failure and lets Compute Engine throughput grow by adding application nodes. The database must be made highly available separately.
Take quiz
only the database
the web server and the Compute Engine
only the scanner
the HTML templates
the scanner CLI
the shared database
46. How do you monitor the health of a SonarQube instance?
Use several layers together:
- System Info page (Administration > System) for JVM, Elasticsearch, DB and CE state.
/api/system/statusfor a basic UP or STARTING check, and/api/system/healthfor GREEN, YELLOW or RED (needs admin rights or the system passcode).- Logs:
sonar.log,web.log,ce.log,es.logandaccess.log. - Prometheus metrics from the monitoring endpoint, scraped with the system passcode, to alert on queue length, memory and Elasticsearch status.
curl https://sonar.example.com/api/system/status curl -H "X-Sonar-Passcode: $SONAR_PASSCODE" https://sonar.example.com/api/system/health
Also watch free disk space, because Elasticsearch turns read-only when the disk is nearly full.
Take quiz
YELLOW
GREEN
BLUE
the scanner stops reading sources
Elasticsearch goes read-only when the disk is nearly full
quality gates are deleted
47. How do you troubleshoot slow SonarQube analysis?
First find where the time goes: scanner side or server side. Run the scanner with -X to get debug timings per sensor, and check the Background Tasks page for time spent in the Compute Engine.
- Scanner memory: raise the heap with
SONAR_SCANNER_OPTS=-Xmx4gif you see GC pressure or OutOfMemory. - Scope: exclude generated code,
node_modules, minified bundles and build output. - SCM blame: slow on huge histories. Fix shallow clones and avoid disabling SCM unless needed, since that loses new-code accuracy.
- Server side: look at CE queue length, database latency and Elasticsearch health.
- Parallel jobs: many simultaneous analyses on a single CE worker queue up.
export SONAR_SCANNER_OPTS="-Xmx4g" sonar-scanner -X -Dsonar.exclusions=**/node_modules/**,**/dist/**
Take quiz
-Q
--silent-mode
-X
exclude generated code and dependency folders
delete the database
disable the quality gate
48. How can you write custom rules for SonarQube?
There are three realistic routes, from easiest to heaviest:
- External linters: write the rule in ESLint, Checkstyle or similar and import the results as external issues.
- Language-specific custom rule plugin: for Java, use the sonar-java API and package the rule in a plugin JAR placed in
extensions/plugins. - Full plugin using the SonarQube Plugin API, for new sensors or languages.
@Rule(key = "NoSystemExit") public class NoSystemExitCheck extends IssuableSubscriptionVisitor { @Override public List<Tree.Kind> nodesToVisit() { return List.of(Tree.Kind.METHOD_INVOCATION); } @Override public void visitNode(Tree tree) { MethodInvocationTree call = (MethodInvocationTree) tree; if ("System.exit".equals(call.methodSelect().toString())) { reportIssue(tree, "Do not call System.exit()"); } } }
After installing, activate the rule in a quality profile. Plugins are tied to a SonarQube API version, so retest them on every upgrade.
Take quiz
conf/wrapper.conf
extensions/plugins
logs
rename the project
restart the scanner machine
activate it in a quality profile
49. Why does a quality gate pass in the IDE but fail on the SonarQube server?
The IDE and the server are not always checking the same thing. Common causes:
- Different rules: SonarQube for IDE in standalone mode uses a default rule set, while the server uses your quality profile. Fix by using connected mode.
- Deeper analysis on the server: cross-file and taint rules run in full on the server and may flag more.
- Different scope: the gate judges new code by the new code period, which may include more changes than what you edited locally.
- Coverage and duplication: these are only computed in CI. A missing coverage report fails a coverage condition.
- Unreviewed hotspots count toward the gate but are not shown as errors in the IDE.
The IDE is a fast pre-check. The server result is the source of truth.
Take quiz
using connected mode with the project's quality profile
raising the IDE font size
closing unused tabs
syntax highlighting
coverage on new code
file encoding in the editor
50. How do you troubleshoot SonarQube showing 0% coverage?
Zero coverage almost always means the report was not found or its paths do not match. Check the scanner log for a line from the coverage importer (for Java, the JaCoCo XML Report Importer) and work through these causes:
- Report not generated: tests did not run before the scan, or coverage was not enabled.
- Wrong property or format: JaCoCo needs the XML report path, JavaScript needs
sonar.javascript.lcov.reportPaths, Python needs a Cobertura-style XML, and so on. - Path mismatch: the report lists
/app/src/...from a Docker build, but the scanner sees/workspace/src/.... Rewrite paths or run the scan in the same location. - Files excluded or outside sonar.sources: coverage is ignored for files that SonarQube does not index.
- Multi-module builds: aggregate reports or list each module report path.
sonar-scanner -X 2>&1 | grep -i -E "coverage|jacoco|lcov"
Fix the cause, re-run tests, then analyze again. Coverage values only update with a new analysis.