A Complete Guide to Setting Up SonarQube and SonarScanner for Code Quality

A Complete Guide to Setting Up SonarQube and SonarScanner for Code Quality

Master the setup of SonarQube and SonarScanner to enhance your code quality and streamline your DevOps workflow.

Introduction

In the realm of modern DevOps and software development, code quality is paramount. It directly impacts the maintainability, security, and performance of applications. SonarQube is a powerful static code analysis tool that assists developers in identifying bugs, vulnerabilities, and maintainability issues within their codebases. This comprehensive guide will walk you through the installation and configuration of SonarQube Community Edition v25.2.0.102705 and SonarScanner CLI v7.0.1.4817 on an Ubuntu 24 server, ensuring you can effectively monitor and improve your code quality.

What Is SonarQube?

SonarQube is an open-source platform designed for continuous inspection of code quality. It provides developers with the tools to analyze their code for potential bugs, security vulnerabilities, and code smells, which are indicators of poor design or implementation. By integrating SonarQube into your development workflow, you can maintain high standards of code quality and foster a culture of continuous improvement within your team.

How It Works

SonarQube operates by analyzing your source code and generating reports on various quality metrics. It uses a set of predefined rules to evaluate the code and provides feedback on issues like code duplication, complexity, and potential bugs. Think of it as a health check for your codebase, similar to how a medical check-up assesses a person's health. Just as doctors use various tests to diagnose health issues, SonarQube uses static analysis to identify code issues.

Prerequisites

Before you begin the installation process, ensure you have the following:

  • An Ubuntu 24 server
  • A non-root user with sudo privileges
  • At least 4GB of RAM (8GB recommended)
  • OpenJDK 17
  • PostgreSQL 17.3
  • Nginx (optional, for reverse proxy configuration)

Installation & Setup

Follow these steps to install and configure SonarQube and SonarScanner.

Step 1: Install OpenJDK 17

First, update your package index and install OpenJDK 17:

sudo apt update
sudo apt remove --purge openjdk-* -y  # Remove old Java versions
sudo apt install openjdk-17-jdk -y
java -version  # Verify installation

Step 2: Install PostgreSQL 17.3

Next, install PostgreSQL:

sudo apt install wget gnupg2 -y
wget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | sudo tee /etc/apt/trusted.gpg.d/postgresql.asc > /dev/null
echo "deb http://apt.postgresql.org/pub/repos/apt/ $(lsb_release -cs)-pgdg main" | sudo tee /etc/apt/sources.list.d/pgdg.list
sudo apt update
sudo apt install postgresql-17 postgresql-client-17 -y
sudo systemctl enable --now postgresql

Step 3: Configure PostgreSQL for SonarQube

Configure PostgreSQL to create a user and database for SonarQube:

sudo -u postgres psql
CREATE USER sonarqube WITH PASSWORD 'YourSecurePassword';
CREATE DATABASE sonarqube OWNER sonarqube;
GRANT ALL PRIVILEGES ON DATABASE sonarqube TO sonarqube;
ALTER USER postgres WITH PASSWORD 'YourSecurePassword';
\q

Modify PostgreSQL settings:

sudo nano /etc/postgresql/17/main/postgresql.conf
# Change:
listen_addresses = '*'

Edit the pg_hba.conf file:

sudo nano /etc/postgresql/17/main/pg_hba.conf
# Add:
host    all             all             0.0.0.0/0    md5
host    all             all             ::/0         md5

Restart PostgreSQL:

sudo systemctl restart postgresql

Step 4: Install and Configure SonarQube

Download and set up SonarQube:

wget https://binaries.sonarsource.com/Distribution/sonarqube/sonarqube-25.2.0.102705.zip
sudo apt install unzip -y
unzip sonarqube-25.2.0.102705.zip
sudo mv sonarqube-25.2.0.102705 /opt/sonarqube
sudo useradd -m -d /opt/sonarqube -s /bin/bash sonarqube
sudo chown -R sonarqube:sonarqube /opt/sonarqube
sudo chmod -R 775 /opt/sonarqube

Configure SonarQube properties:

sudo nano /opt/sonarqube/conf/sonar.properties
# Add:
sonar.jdbc.username=sonarqube
sonar.jdbc.password=YourSecurePassword
sonar.jdbc.url=jdbc:postgresql://localhost:5432/sonarqube
sonar.web.host=0.0.0.0
sonar.web.port=9000

Step 5: Create a Systemd Service for SonarQube

Create a service file for SonarQube:

sudo nano /etc/systemd/system/sonarqube.service
# Add the following content:
[Unit]
Description=SonarQube service
After=network.target postgresql.service

[Service]
Type=simple
ExecStart=/opt/sonarqube/bin/linux-x86-64/sonar.sh start
ExecStop=/opt/sonarqube/bin/linux-x86-64/sonar.sh stop
User=sonarqube
Group=sonarqube
Restart=always
LimitNOFILE=65536

[Install]
WantedBy=multi-user.target

Enable and start the SonarQube service:

sudo systemctl enable sonarqube
sudo systemctl start sonarqube

Real-World Examples

Example 1: Basic Code Analysis

After setting up SonarQube, you can analyze a Java project. Create a sonar-project.properties file in your project directory:

sonar.projectKey=my_project
sonar.projectName=My Project
sonar.projectVersion=1.0
sonar.sources=src
sonar.java.binaries=bin

Run SonarScanner:

sonar-scanner

Example 2: Integration with CI/CD

Integrate SonarQube with your CI/CD pipeline (e.g., Jenkins):

pipeline {
    stages {
        stage('Build') {
            steps {
                sh 'mvn clean install'
            }
        }
        stage('SonarQube Analysis') {
            steps {
                script {
                    def scannerHome = tool 'SonarScanner'
                    withSonarQubeEnv('SonarQube') {
                        sh "${scannerHome}/bin/sonar-scanner"
                    }
                }
            }
        }
    }
}

Best Practices

  • Regularly update SonarQube and SonarScanner to the latest versions.
  • Configure quality gates to enforce code quality standards.
  • Integrate SonarQube into your CI/CD pipeline for continuous feedback.
  • Use custom rules tailored to your project's coding standards.
  • Monitor SonarQube dashboards regularly to track code quality trends.
  • Ensure that all team members are trained on using SonarQube effectively.
  • Backup your SonarQube database regularly to prevent data loss.

Common Issues & Fixes

Issue Cause Fix
SonarQube fails to start Insufficient memory Increase server RAM to at least 8GB.
Database connection error Incorrect database settings Verify sonar.properties configurations.
Scanner fails to analyze project Missing sonar-project.properties Create the file with correct settings.

Key Takeaways

  • SonarQube is essential for maintaining high code quality.
  • The installation process involves setting up OpenJDK, PostgreSQL, and SonarQube itself.
  • Configuring SonarQube with PostgreSQL is crucial for data storage.
  • Integrating SonarScanner allows for seamless code analysis.
  • Regular monitoring and updates are necessary to maintain effectiveness.
  • Best practices help ensure that your use of SonarQube is efficient and beneficial.

Responses

Sign in to leave a response.

Loading…