How-to add SonarQube Checks to a Gradle Build

This post is about how-to integrate SonarQube into your Gradle powered development process with Docker and Jenkins.

SonarQube - The leading product for Continuous Code Quality”

Gradle with SonarQube

Integrating SonarQube into your Gradle build is as easy as adding the plugin org.sonarqube with:

plugins {
  id "org.sonarqube" version "2.6.2"
}

and running the command ./gradlew sonarqube. Add the System property -Dsonar.host.url=http://<hostname>:<port> in case your service is not running locally…

Since this wouldn’t be worth a post I decided to add two bonus chapters ;-)

Bonus I: Run SonarQube with Docker Compose

In the following Setup, we’ll use the official Docker image for SonarQube: sonarqube.

The main piece infrastructure wise is the docker-compose.yaml file:

  sonarqube:
    image: sonarqube:6.7.5-alpine
    depends_on:
      - postgres
    volumes:
      - sonarqube:/opt/sonarqube
    links:
      - postgres:db
    ports:
      - 127.0.0.1:9000:9000



volumes:
  sonarqube:

With docker-compose up sonarqube you can spin up your local SonarQube which will be available on port 9000

Tip: If you want to use a PostgreSQL as backend you might want to have a look at our post Using a PostgreSQL with Docker like a Pro covering the database part of this scenario.

You’ll also need to configure the database connection in your sonar environment:

    environment:
      - SONARQUBE_JDBC_URL=jdbc:postgresql://postgres:5432/sonar
      - SONARQUBE_JDBC_USERNAME=sonar
      - SONARQUBE_JDBC_PASSWORD=jenkins

Bonus II: Run SonarQube behind NGinx

In case you want a simple basic authentication before your SonarQube instance you can add the following snippet to your NGinx configuration:

location ^~ /sonar { proxy_set_header Host $host; proxy_set_header X-Forwarded-Host $host; proxy_set_header X-Forwarded-Server $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header Authorization ""; auth_basic “SonarQube”; auth_basic_user_file /etc/sonarqube/htaccess; proxy_pass http://127.0.0.1:9000; }

Note: Did you spot the Authorization ""; header, which gave me some headaches…?!

In the docker-compose.yaml we added a command: -Dsonar.web.context=/sonar to be passed to the entry point to change the context to match our NGinx location.

Safer coding…with Quality Gates