书续前文,前面使用Jenkins-maven构建的方式,搭建了持续集成环境。
Pipeline介绍:
是一套运行于Jenkins上的工作流框架,将原本独立运行于单个或者多个节点的任务连接起
来,实现单个任务难以完成的复杂流程编排与可视化。
Pipeline的实现方式是一套GroovyDSL,任何发布流程都可以表述为一段Groovy脚本,并且
Jenkins支持从代码库直接读取脚本,从而实现了PipelineasCode的理念。将原本独立运行于多个Job或者多个节点的任务统一使用代码的形式进行管理和维护。
发布流程设计
目录
1、新建Jenkins JOB任务
2、定义Jenkinsfile脚本文件内容
3、Jenkins构建执行Jenkinsfile脚本
4、测试执行结果
1、新建Jenkins JOB任务
新建任务:
设置gitURL及认证信息
其中,上面这个凭证信息,可以从全局凭证里添加
2、定义Jenkinsfile脚本文件内容
整体上分为4个步骤阶段:
1、准备阶段:git上拉取代码,定义镜像文件名字等信息
2、编译构建阶段:使用maven工具编译jar包,使用docker-build工具,制作image镜像
3、把镜像推送到仓库:登录腾讯云镜像仓库(登录 - 腾讯云),把镜像推送到指定的命名空间
4、从镜像仓库拉取镜像,发布到线上:登录腾讯云镜像,拉取刚刚推送的镜像文件,在docker里运行发布
node {
stage('Prepare') {
echo "1.Prepare Stage"
checkout scm
pom = readMavenPom file: 'pom.xml'
docker_host = "ccr.ccs.tencentyun.com"
img_name = "${pom.groupId}/${pom.artifactId}"
docker_img_name = "${docker_host}/${img_name}"
echo "group: ${pom.groupId}, artifactId: ${pom.artifactId}, version: ${pom.version}"
echo "docker-img-name: ${docker_img_name}"
script {
build_tag = sh(returnStdout: true, script: 'git rev-parse --short HEAD').trim()
if (env.BRANCH_NAME != 'main' && env.BRANCH_NAME != null) {
build_tag = "${env.BRANCH_NAME}-${build_tag}"
}
}
}
stage('Build') {
echo "2.Build Docker Image Stage"
def mvnHome = tool 'maven3.8.3'
withMaven(maven : 'maven3.8.3') {
sh "mvn package -Dmaven.test.skip=true"
}
sh "docker build -t ${docker_img_name}:${build_tag} " +
" --build-arg SPRING_PROFILE=prod " +
" --build-arg JAR_FILE=target/${pom.artifactId}-${pom.version}.jar " +
" ."
}
stage('Push') {
echo "3.Deploy jar and Push Docker Image Stage"
sh "docker tag ${docker_img_name}:${build_tag} ${docker_img_name}:${pom.version}"
withCredentials([usernamePassword(credentialsId: 'tengxunyun', passwordVariable: 'dockerPassword', usernameVariable: 'dockerUser')]) {
sh "docker login -u ${dockerUser} -p ${dockerPassword} ccr.ccs.tencentyun.com"
sh "docker push ${docker_img_name}:${pom.version}"
}
echo "push ok"
}
stage('deploy') {
echo "4.Deploy to line"
withCredentials([usernamePassword(credentialsId: 'tengxunyun', passwordVariable: 'dockerPassword', usernameVariable: 'dockerUser')]) {
sh "docker login -u ${dockerUser} -p ${dockerPassword} ccr.ccs.tencentyun.com"
sh "docker pull ${docker_img_name}:${pom.version}"
sh "docker run -d -p 58080:58080 ${docker_img_name}:${pom.version}"
}
echo "push ok"
}
}
其中第3步登录腾讯云镜像时,需要凭证信息 (withCredentials),需要预先在Jenkins中设置上,如下:
推送到的腾讯云镜像仓库:
3、Jenkins构建执行Jenkinsfile脚本
点击Jenkins构建
推送镜像成功:
拉取镜像,并在docker发布成功
登录虚拟机,查看发布的应用: