Operations 8 min read

Streamline Jenkins Pipelines with Shared Libraries: A Step-by-Step Guide

This tutorial explains how to use Jenkins shared libraries to consolidate repetitive pipeline code, set up Jenkins with Docker Compose, define reusable Groovy methods, create Docker build files, and configure pipeline jobs for maintainable, version‑controlled CI/CD workflows.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Streamline Jenkins Pipelines with Shared Libraries: A Step-by-Step Guide

Introduction

When multiple Jenkins pipelines contain duplicated code, maintaining them becomes cumbersome; using a shared library lets you encapsulate common logic and call it from any pipeline, improving maintainability and version control.

Install Jenkins

Run Jenkins via Docker Compose:

$ mkdir jenkins && cd jenkins
$ sudo mkdir -p data
$ sudo chown 1000.1000 -R data
$ vim docker-compose.yml
version: '3.9'
services:
  jenkins-master:
    image: docker.io/jenkins/jenkins:2.377-jdk17
    container_name: jenkins
    hostname: jenkins
    restart: always
    privileged: true
    network_mode: 'host'
    volumes:
      - /etc/localtime:/etc/localtime:ro
      - ./data:/var/jenkins_home
    environment:
      - JAVA_OPTS='-Djava.util.logging.config.file=/var/jenkins_home/log.properties'
      - TZ=Asia/Shanghai

After starting Jenkins, install the Pipeline: Groovy Libraries and List Git Branches Parameter plugins.

Create a Shared Library

Prepare a Git repository with the following structure:

.
├── resources   # files needed during the build
│   └── build
│       └── mvn
│           ├── Dockerfile
│           └── settings.xml
├── src         # reusable Groovy classes
│   └── org
│       └── devops
│           ├── GlobalVars.groovy
│           └── tools.groovy
└── vars        # pipeline scripts
    └── pipeline01

Define common build methods in tools.groovy:

package org.devops

def gitCheckout(URL, credentialsId) {
    steps.checkout([
        $class: 'GitSCM',
        branches: [[name: '$BRANCH']],
        extensions: [],
        userRemoteConfigs: [[credentialsId: "${credentialsId}", url: "${URL}"]]
    ])
}

def gitMsg() {
    sh '''
        git show --stat --format=提交日期:%ci,%n提交人:%cn,%n提交备注:%s,%n提交Hash:%H,%n提交分支:%d,%n%b%n提交修改的文件:
    '''
}

def cleanWS() {
    cleanWs deleteDirs: true, notFailBuild: true
}

def creatFile(filename, content) {
    steps.writeFile encoding: 'UTF-8', file: "$filename", text: "$content"
}

def commitId() {
    String commit = steps.sh(returnStdout: true, script: 'git rev-parse --short HEAD').trim()
    return commit
}

def build(action, commitid, repourl, tag) {
    sh """
       # build
       DOCKER_BUILDKIT=1 docker build --progress=auto \
                 --target=${action} \
                 --build-arg version=${commitid} \
                 -t ${repourl}:${tag} .
       # push
       docker push ${repourl}:${tag} && docker rmi ${repourl}:${tag}
    """
}

def loginRepo(username, password, repourl) {
    sh """
      docker login -u $username -p $password $repourl
    """
}

Define global variables in GlobalVars.groovy:

package org.devops

class GlobalVars {
    static String giturl = 'https://example.com/example/test.git'
    static String certid = 'e6655bac-85cc-4a61-9ae3-3eeb02ff2e4c'
    static String imageRepo = 'harbor.example.cn/public'
    static String pushRepo = 'harbor.example.cn/public/test'
    static String userRepo = 'root'
    static String passRepo = 'root1234'
}

Define the Pipeline

@Library('jenkinslibrary@master') _

def GlobalVars = new org.devops.GlobalVars()

def tools = new org.devops.tools()

def buildfile = libraryResource "build/mvn/Dockerfile"

def mvnconf = libraryResource "build/mvn/settings.xml"

pipeline {
    agent any
    options {
        buildDiscarder logRotator(artifactDaysToKeepStr: '', artifactNumToKeepStr: '', daysToKeepStr: '5', numToKeepStr: '5')
        disableConcurrentBuilds()
        disableResume()
        skipDefaultCheckout()
        timestamps()
    }
    stages {
        stage('拉取代码') {
            steps {
                script {
                    tools.gitCheckout(GlobalVars.giturl, GlobalVars.certid)
                    tools.gitMsg()
                }
            }
        }
        stage('构建镜像') {
            steps {
                script {
                    def commitID = tools.commitId()
                    def imagetag = currentBuild.id
                    tools.creatFile('settings.xml', mvnconf)
                    tools.creatFile('Dockerfile', buildfile)
                    tools.loginRepo(GlobalVars.userRepo, GlobalVars.passRepo, GlobalVars.imageRepo)
                    tools.build('release', commitID, GlobalVars.pushRepo, imagetag)
                }
            }
        }
    }
    post {
        always {
            script { tools.cleanWS() }
        }
    }
}

Create Build Files

Dockerfile :

FROM docker.io/library/maven:3.8-openjdk-8-slim AS build
ENV TZ=Asia/Shanghai
RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && \
    echo $TZ > /etc/timezone
WORKDIR /build
COPY settings.xml /root/.m2/
COPY . /build
RUN mvn -Dmaven.test.skip=true package

FROM docker.io/library/eclipse-temurin:8u332-b09-jre-focal AS release
ENV TZ=Asia/Shanghai
ARG version
EXPOSE 8080
WORKDIR /app
COPY --from=build /build/target/test-0.0.1-SNAPSHOT.jar app.jar
ENTRYPOINT java -server \
           ${JAVA_OPTS} \
           -jar /app/app.jar \
           --user.timezone=GMT+08 \
           --java.security.egd=file:/dev/./urandom ${JAVA_CLI}

settings.xml (Maven mirrors configuration) is also added to the repository.

Add the Shared Library in Jenkins

Navigate to Manage Jenkins → Global Pipeline Libraries and configure the library repository.

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/cdPipelineGroovyShared LibraryJenkins
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

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.