Setting Up SonarQube Locally with Docker Compose

SonarQube is a powerful open-source platform for continuous inspection of code quality. It helps developers detect and fix bugs, vulnerabilities, and code smells early in the development process. Running SonarQube locally with Docker Compose is a convenient way to experiment and integrate it into your development workflow.

Prerequisites

  • Docker and Docker Compose installed on your local machine.
  • A PostgreSQL database running locally or accessible via network.

Setting Up Docker Compose

  1. Create a Docker Compose file: Save the following configuration as docker-compose.yml
version: "3"

services:
  sonarqube:
    image: sonarqube:9.9.6-community
    depends_on:
      - db
    environment:
      SONAR_JDBC_URL: jdbc:postgresql://postgres:5432/sonar
      SONAR_JDBC_USERNAME: postgres
      SONAR_JDBC_PASSWORD: passwd
    ports:
      - "9000:9000"
    volumes:
      - sonarqube_data:/opt/sonarqube/data
      - sonarqube_extensions:/opt/sonarqube/extensions
      - sonarqube_logs:/opt/sonarqube/logs
  db:
    image: postgres:12
    environment:
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD: passwd
    volumes:
      - postgresql:/var/lib/postgresql
      - postgresql_data:/var/lib/postgresql/data

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

2. Run Docker Compose: Execute the following command in your terminal:

docker-compose up -d

This will start SonarQube and the PostgreSQL database containers in the background.

Running SonarScanner

Assuming your project is stored in /absolute/path/to/your/project, you need to run

docker run --rm -v "/absolute/path/to/your/project:/usr/src" -e SONAR_HOST_URL=http://localhost:9000 --network=sonarqube_default sonarsource/sonar-scanner-cli

The example above assumes you have a sonar-project.properties file present in your project root.