Code analysis with SonarQube

SonarQube is a tool to do static code analysis, also known as Static Application Security Testing (SAST).

It’s a great tool to find security and quality issues in your code.

Install SonarQube

To install SonarQube, we’ll use Docker and docker-compose.yml file.

Here a ready to use and updated docker-compose.yml file to install SonarQube with PostgreSQL database:

services:
  sonarqube:
    image: sonarqube:community
    hostname: sonarqube
    container_name: sonarqube
    read_only: true
    depends_on:
      db:
        condition: service_healthy
    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
      - sonarqube_temp:/opt/sonarqube/temp
    ports:
      - "9000:9000"
  db:
    image: postgres:17
    healthcheck:
      test: ["CMD-SHELL", "pg_isready"]
      interval: 10s
      timeout: 5s
      retries: 5
    hostname: postgresql
    container_name: postgresql
    environment:
      POSTGRES_USER: sonar
      POSTGRES_PASSWORD: sonar
      POSTGRES_DB: sonar
    volumes:
      - postgresql:/var/lib/postgresql
      - postgresql_data:/var/lib/postgresql/data

volumes:
  sonarqube_data:
  sonarqube_temp:
  sonarqube_extensions:
  sonarqube_logs:
  postgresql:
  postgresql_data:

Start containers:

docker compose up -d

SonarQube is now running on port 9000.

On the first start, you can login with admin:admin and SonarQube will ask you to change your password.

Configure SonarQube Project

Once SonarQube is running, we need to creatte a news project.

In our case, we’ll create a local project. But it is also possible to connect SonarQube to GitHub or Gitlab.

  1. Click on Create a local project, name your project and take care of the Project key. Validate, then use global setting
  2. Once again, we’ll scan a local project, so select Locally
  3. Create a token, save it, we’ll use it later

Run analysis with Sonar Scanner

Go to your project folder. You need to create a file named sonar-project.properties with the following content and your project key:

sonar.projectKey=<project key>

We are now ready to run analysis with Sonar Scanner, do not forget to replace myAuthenticationToken with your token and set your variables:

docker run \
    --rm \
    -e SONAR_HOST_URL="http://${SONARQUBE_URL}"  \
    -e SONAR_TOKEN="myAuthenticationToken" \
    -v "${YOUR_REPO}:/usr/src" \
    sonarsource/sonar-scanner-cli

After few seconds or minutes, SonarQube will show results on your project page.

You are ready to fix issues and re-run analysis to see evolution.

Sources