Operations 4 min read

Creating a SonarScanner Docker Image and Jenkinsfile for Automated Code Scanning

This guide explains how to build a Docker image that bundles a Jenkins slave with Maven and SonarScanner, and provides a Jenkinsfile that runs SonarScanner inside a Kubernetes pod to perform fast, automated code analysis as part of a CI/CD pipeline.

DevOps Cloud Academy
DevOps Cloud Academy
DevOps Cloud Academy
Creating a SonarScanner Docker Image and Jenkinsfile for Automated Code Scanning

To speed up code scanning using containers, the guide shows how to build a Docker image that includes a Jenkins slave, Maven, and SonarScanner, and then demonstrates a Jenkinsfile that runs the scanner in a Kubernetes pod.

First, a Dockerfile is created based on the official Jenkins slave image, adding the Apache Maven and Sonar‑Scanner archives:

FROM registry.it.com/jenkins/jenkins-slave:latest
#tool maven
ADD apache-maven-3.5.0.tar.gz /usr/local/
#tool sonar
ADD sonar-scanner.tar.gz /usr/local/

The Jenkinsfile defines a SonarScan Groovy function that selects the appropriate classpath, invokes sonar-scanner with project‑specific parameters, and handles errors.

def label = "mypod-${UUID.randomUUID().toString()}"
//代码扫描
def SonarScan(projectType,skipSonar,srcDir,serviceName){
    def scanHome = "/usr/local/sonar-scanner"
    if (projectType == 'java'){
        if ("${buildType}" == 'gradle'){
            codepath = 'build/classes'
        } else{
            codepath = 'target/classes'
        }
        try {
            sh """
                cd ${srcDir}
                ${scanHome}/bin/sonar-scanner -Dsonar.projectName=${serviceName} -Dsonar.projectKey=${serviceName} \
                -Dsonar.sources=src/main -Dsonar.tests=src/test -Dsonar.language=java -Dsonar.sourceEncoding=UTF-8 \
                -Dsonar.java.binaries=${codepath} -Dsonar.java.coveragePlugin=jacoco \
                -Dsonar.jacoco.reportPath=target/jacoco.exec -Dsonar.junit.reportsPath=target/surefire-reports \
                -Dsonar.surefire.reportsPath=target/surefire-reports -Dsonar.projectDescription='devopsdevops'
            """
        } catch (e){
            currentBuild.description="代码扫描失败!"
            error '代码扫描失败!'
        }
    }
}

Using podTemplate, the pipeline runs on a Kubernetes pod with the custom image, allocating CPU and memory resources and mounting a persistent volume for workspace data.

podTemplate(
    label: label,
    cloud: 'kubernetes',
    containers: [
        containerTemplate(
            name: 'jnlp',
            image: 'registry.it.com/jenkins/slave-maven-sonar-jdk8u111:latest',
            ttyEnabled: true,
            privileged: false,
            alwaysPullImage: true,
            args: '${computer.jnlpmac} ${computer.name}',
            resourceRequestCpu: '4000m',
            resourceLimitCpu: '8000m',
            resourceRequestMemory: '8Gi',
            resourceLimitMemory: '16Gi',
            envVars: [
                envVar(key: 'PATH', value: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/local/apache-maven-3.5.0/bin'),
                envVar(key: 'CLASS_PATH', value: '/docker-java-home/jre/lib/rt.jar:/docker-java-home/jre/lib/dt.jar:/docker-java-home/jre/lib/tools.jar')
            ]
        )
    ],
    volumes: [persistentVolumeClaim(mountPath: '/etc/data/', claimName: 'jenkins')],
    slaveConnectTimeout: '60'
){
    node(label) {
        ws("${workspace}"){
            stage('GetCode'){ /* ... */ }
            stage('Build'){ /* ... */ }
            stage('CodeScan'){
                SonarScan('java',skipSonar,srcDir,serviceName)
            }
        }
    }
}

By following these steps, developers can quickly set up a reproducible environment for automated SonarQube analysis within their CI/CD pipelines.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Dockerci/cdKubernetesDevOpsJenkinsSonarScanner
DevOps Cloud Academy
Written by

DevOps Cloud Academy

Exploring industry DevOps practices and technical expertise.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.