Jenkins packaging microservices to build Docker images and run them

Jenkins packaging microservices to build Docker images and run them

Environment Preparation

1.Jenkins
2. GitLab
3.SonarQube
4. Harbor
5.Docker
6. Maven
7. JDK1.8
8. Microservice Project

The above technical part has been written in my previous article

There is no detailed demonstration here. This article mainly coherently converts the microservice project source code -> submit to the remote repository GitLab -> Jenkins pulls the code from Gitlab to the server -> SonarQube code review -> Maven compiles and packages -> builds Docker images -> pushes to the private Harbor image repository -> deploys to other servers

start

1. GitLab remote repository creates a microservice project

insert image description here

2. IDEA code is pushed to Gitlab

insert image description here

The default folder is correct, so there is no need to change it.

insert image description here

Add a local repository

insert image description here

Submit local repository

insert image description here

Push remote repository

insert image description here

3.Jenkins creates a pipeline project

insert image description here

4. Parameterized construction

insert image description here

5. Pull the build script of the remote repository

insert image description here

Application Save

6. Write the remote review script sonar-project.properties

insert image description here

Build Scripts

1. Pull code

stage('Pull code') {
      checkout([$class: 'GitSCM', branches: [[name:"*/${branch}"]], doGenerateSubmoduleConfigurations: false, extensions: [], submoduleCfg: [], userRemoteConfigs: [[credentialsId: "${git_auth}", url: "${git_url}"]]])
   }

insert image description here

insert image description here

2. Review the code

stage('code review') {
            //Define the current Jenkins's SonarQubeScanner tool def scannerHome = tool 'SonarQube'
            //Reference the current JenkinsSonarQube environment withSonarQubeEnv('SonarQube') {
                 sh """
                         cd ${project_name}//This is the defined option parameter ${scannerHome}/bin/sonar-scanner
                 """
            }
   }

insert image description here
insert image description here

3. Install common modules

 stage('compile, install common sub-projects') {
      sh "mvn -f tensquare_common clean install"
   }

insert image description here

View Server

insert image description here

4. Compile and package microservices

 stage('compile, package microservice project') {
         sh "mvn -f ${project_name} clean package"
   }

insert image description here

View Server

insert image description here

Build process so far

insert image description here

5. Add Dockerfile file to build docker image project,

insert image description here

#FROM java:8
#FROM openjdk:11-jdk-alpine
FROM openjdk:11
ARG JAR_FILE
COPY ${JAR_FILE} app.jar
EXPOSE 9001
ENTRYPOINT ["java","-jar","/app.jar"]

Add a dockerfile plugin to each microservice project Maven

			<plugin>
                <groupId>com.spotify</groupId>
                <artifactId>dockerfile-maven-plugin</artifactId>
                <version>1.3.6</version>
                <configuration>
                    <repository>${project.artifactId}</repository>
                    <buildArgs>
                        <JAR_FILE>target/${project.build.finalName}.jar</JAR_FILE>
                    </buildArgs>
                </configuration>
            </plugin>

Modify the Jenkinsfile file service packaging and add "dockerfile:build" to trigger the docker image build

 stage('compile, package microservice project') {
         sh "mvn -f ${project_name} clean package dockerfile:build"
   }

And push to the remote warehouse

Jenkins Rebuild

insert image description here

View Server

docker images 

insert image description here

Image build successful

6. Image tagging

Public Properties

//Mirror version number def tag = "latest"
//Harbor's url address def harbor_url = "192.168.0.188:9123"
//Mirror library project name def harbor_project = "tensquare"
 stage('compile, package microservice project and upload image') {
         //Compile and package -- build image sh "mvn -f ${project_name} clean package dockerfile:build"

         //Define the image name def imageName = "${project_name}:${tag}"

         //Tag the image sh "docker tag ${imageName} ${harbor_url}/${harbor_project}/${imageName}"
   }

Push to remote server and build Jenkins to view server image

insert image description here

7. Push the image to the harbor private warehouse. Here you need to withdraw money and create a warehouse on Harbor.
Jenkins adds harbor user credentials

insert image description here

Enter the pipeline syntax to generate harbor syntax

insert image description here

stage('compile, package microservice project and upload image') {
         //Compile and package -- build image sh "mvn -f ${project_name} clean package dockerfile:build"


         //Define the image name def imageName = "${project_name}:${tag}"

         //Tag the image sh "docker tag ${imageName} ${harbor_url}/${harbor_project}/${imageName}"

         //Push the image to Harbor
         withCredentials([usernamePassword(credentialsId: "${harbor_auth}", passwordVariable: 'password', usernameVariable: 'username')]) {
             //Log in to Harbor
             sh "docker login -u ${username} -p ${password} ${harbor_url}"
             //Image upload sh "docker push ${harbor_url}/${harbor_project}/${imageName}"
             sh "echo image upload successful"
         }
   }

Push remote warehouse, Jenkins remote build, view the image pushed to the private warehouse

insert image description here

Remote push image successful! ! !

8. Pull the image and start the program. Since you need to pull the image and start the program remotely, you need to install the Publish Over SSH plug-in on Jenkins first to send Shell commands remotely.

insert image description here

Configuring the plugin

insert image description here

It should be noted here that the two servers need to establish communication and use ssh remote connection, that is, Jenkins uses ssh to remotely operate the 188 server to pull the image. In the process of starting the application, the host server of Jenkins needs to generate the public key and private key and then copy them to the 188 server.
1. Switch to the ssh directory

cd /root/.ssh
If prompted: bash: cd: .ssh: no such file or directory execute ssh hostname (your own host name)

2. Execute the command to generate public and private keys on the Jenkins host server

ssh-keygen -t rsa

Then compare the following

insert image description here

id_rsa is the private key id_rsa.pub is the public key

3. Copy the public key id_rsa.pub to the 188 server

ssh-copy-id 192.168.0.188

4. Check the key copied to the 188 server

insert image description here

5. Test Jenkins' ssh remote connection

insert image description here

Test success

6. Use the pipeline syntax generator to generate ssh commands

insert image description here

Copy to Jenkinsfile

   //Application deployment sh "echo application deployment"
         sshPublisher(publishers: [sshPublisherDesc(configName: '188', transfers: [sshTransfer(cleanRemote: false, excludes: '', execCommand: "/data/Jenkins_shell/deploy.sh $harbor_url $harbor_project $project_name $tag $port", execTimeout: 120000, flatten: false, makeEmptyDirs: false, noDefaultExcludes: false, patternSeparator: '[, ]+', remoteDirectory: '', remoteDirectorySDF: false, removePrefix: '', sourceFiles: '')], usePromotionTimestamp: false, useWorkspaceInPromotion: false, verbose: false)])


/data/Jenkins_shell/deploy.sh This path points to a script file used to operate the docker container. This script is provided below $harbor_url The private repository address of the image $harbor_project The project name in the private repository $project_name The project name $tag The version of the image to be pulled $port This parameter also needs to be provided in the Jenkins build These parameters correspond one-to-one to the parameters in this file
#!/bin/sh
#Receive external parameter harbor_url=$1
harbor_project=$2
project_name=$3
tag=$4
port=$5

imageName=$harbor_url/$harbor_project/$project_name:$tag

echo "$imageName"

#Check if the container exists, if it exists, delete it containerId=`docker ps -a | grep -w ${project_name}:${tag} | awk '{print $1}'`
if [ "$containerId" != "" ] ; then
    #Stop the container docker stop $containerId

    #Delete the container docker rm $containerId
	
	echo "Container deleted successfully"
fi

#Query whether the image exists, if it exists, delete it imageId=`docker images | grep -w $project_name | awk '{print $3}'`

if [ "$imageId" != "" ] ; then
      
    #Delete the image docker rmi -f $imageId
	
	echo "Successfully deleted the image"
fi

# Log in to Harbor
docker login -u user -p 877425287User $harbor_url

# Download the image docker pull $imageName

# Start the container docker run -di -p $port:$port $imageName

echo "Container started successfully"

Add Jenkins input

insert image description here

Submit the code and start building

insert image description here

Build Success

insert image description here

Code Review SonarQube

insert image description here

Mirror repository Harbor

insert image description here

188 Mirror image pulled from remote server

insert image description here

Check the container startup status

insert image description here

Accessing the test container

insert image description here

This is the end of this article about Jenkins packaging microservices to build Docker images and run them. For more information about Jenkins packaging and building Docker images, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Detailed steps for springboot docker jenkins to automatically deploy and upload images
  • How to build a Docker image based on Jenkins
  • Jenkins builds Docker image example

<<:  The idea and process of Vue to realize the function of remembering account and password

>>:  This article will show you the principle of MySQL master-slave synchronization

Recommend

HTML basics HTML structure

What is an HTML file? HTML stands for Hyper Text M...

Vue3 Documentation Quick Start

Table of contents 1. Setup 1. The first parameter...

Create a custom system tray indicator for your tasks on Linux

System tray icons are still a magical feature tod...

View the dependent libraries of so or executable programs under linux

View the dependent libraries of so or executable ...

How to elegantly back up MySQL account information

Preface: I recently encountered the problem of in...

Comparing Document Locations

<br />A great blog post by PPK two years ago...

Detailed explanation of JavaScript onblur and onfocus events

In HTML pages, visual elements such as buttons an...

The complete implementation process of Sudoku using JavaScript

Table of contents Preface How to solve Sudoku Fil...

Installation tutorial of mysql 8.0.11 compressed version under win10

This article shares the installation tutorial of ...

Layui implements sample code for multi-condition query

I recently made a file system and found that ther...

Method of dynamically loading geojson based on Vue+Openlayer

Load one or more features <template> <di...

Summary of commonly used CSS encapsulation methods

1. pc-reset PC style initialization /* normalize....