Hi folks, In this article, I'll show you a simple way to install SonarQube and analyze your code.
Preconditions
Please install and run Docker Desktop. And generate the simple project from the template:
dotnet new webapi --use-controllers -o SonarQubeSample cd SonarQubeSample Configuration
Now open the project in your favorite IDE, create the sonarqube.yml file, and paste this code:
version: "3" 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 volumes: - sonarqube_data:/opt/sonarqube/data - sonarqube_extensions:/opt/sonarqube/extensions - sonarqube_logs:/opt/sonarqube/logs ports: - "9000:9000" db: image: postgres:12 environment: POSTGRES_USER: sonar POSTGRES_PASSWORD: sonar volumes: - postgresql:/var/lib/postgresql - postgresql_data:/var/lib/postgresql/data volumes: sonarqube_data: sonarqube_extensions: sonarqube_logs: postgresql: postgresql_data: This script will install SonarQube and PostgreSQL images. You can run it from the project's folder:
docker compose -f sonarqube.yml up You should see something like this:
Now go to the browser and go to the link: http://localhost:9000. And login using Login: admin and Password: admin.
SonarQube will ask you to change the password. Please do it. Next, go to the http://localhost:9000/account/security link. You need to generate a token.
Type any name, select Global Analysis Token type, and any expiration days. Copy this token. You won't be able to copy it when you leave or refresh this page.
Analysis
For convenience, I created a PowerShell script. I also created a bash script, which you can find in the repo. Add this code, but you can use it separately:
# Check if dotnet-sonarscanner is installed $installedTools = dotnet tool list --global if ($installedTools -notcontains "dotnet-sonarscanner") { Write-Host "dotnet-sonarscanner not found. Installing..." dotnet tool install --global dotnet-sonarscanner } else { Write-Host "dotnet-sonarscanner is already installed." } # Verify the installation dotnet sonarscanner --version # Set the SonarQube token as an environment variable $env:SONAR_TOKEN = "[your sonarqube token]" # Start SonarQube analysis dotnet sonarscanner begin /k:"SonarQubeSample" ` /d:sonar.host.url="http://localhost:9000" ` /d:sonar.token=$env:SONAR_TOKEN # Build the project dotnet build .\SonarQubeSample.csproj --no-incremental # End SonarQube analysis dotnet sonarscanner end /d:sonar.token=$env:SONAR_TOKEN This script installs the dotnet-sonarscanner if needed. Next, it begins analysis, builds project, and ends work. Run it.
# Mac OS pwsh analysis.ps1 # Windows .\analysis.ps1 If you go to the http://localhost:9000/dashboard?id=SonarQubeSample&codeScope=overall link, you'll see the report.
That's all. I hope this article was useful to you. See you next week. Happy coding!





Top comments (1)
great