1. 构建 Jenkins 流水线
使用 Jenkins 构建的流水线 Item 需要完成以下几个操作
- 拉取 Git 仓库代码
- 使用 Maven 构建项目
- 通过 Docker 制作自定义镜像
- 将自定义镜像推送到 Harbor
- 应用服务器拉取镜像
对应的流水线代码如下
pipeline {
agent any
environment {
harborUser = 'admin'
harborPasswd = 'Harbor12345'
harborAddress = '192.168.80.128:80'
harborRepo = 'repo'
tag = 'v1.0.0'
container_port = '8088'
host_port = '8088'
}
stages {
stage('拉取 Git 仓库代码') {
steps {
git credentialsId: 'd2ab9c92-9a55-4c06-9b4e-874fe743ac94', url: 'https://gitee.com/YonminMa/SelectDormitory.git'
echo '拉取 Git 仓库代码 - SUCCESS'
}
}
stage('使用 Maven 构建项目') {
steps {
sh '/usr/local/apache-maven-3.9.0/bin/mvn clean package -DskipTests'
echo '使用 Maven 构建项目 - SUCCESS'
}
}
stage('通过 Docker 制作自定义镜像') {
steps {
sh 'docker build -t ${JOB_NAME}:$tag .'
echo '通过 Docker 制作自定义镜像 - SUCCESS'
}
}
stage('将自定义镜像推送到 Harbor') {
steps {
sh '''docker login -u ${harborUser} -p ${harborPasswd} ${harborAddress}
docker tag ${JOB_NAME}:$tag ${harborAddress}/${harborRepo}/${JOB_NAME}:$tag
docker push ${harborAddress}/${harborRepo}/${JOB_NAME}:$tag'''
echo '将自定义镜像推送到 Harbor - SUCCESS'
}
}
stage('应用服务器拉取镜像') {
steps {
sshPublisher(publishers: [sshPublisherDesc(configName: 'ubuntu', transfers: [sshTransfer(cleanRemote: false, excludes: '', execCommand: "/usr/local/test/deploy.sh $harborAddress $harborRepo $JOB_NAME $tag $container_port $host_port", execTimeout: 120000, flatten: false, makeEmptyDirs: false, noDefaultExcludes: false, patternSeparator: '[, ]+', remoteDirectory: '', remoteDirectorySDF: false, removePrefix: '', sourceFiles: '')], usePromotionTimestamp: false, useWorkspaceInPromotion: false, verbose: false)])
echo '应用服务器拉取镜像 - SUCCESS'
}
}
}
}
2. 应用服务器脚本
在上面的流水线代码中调用了应用服务器的 /usr/local/test/deploy.sh
文件
mkdir -p /usr/local/test/
cd /usr/local/test/
vim deploy.sh
chmod +x deploy.sh
deploy.sh
文件内容如下
harbor_addr=$1
harbor_repo=$2
project=$3
version=$4
container_port=$5
host_port=$6
imageName=$harbor_addr/$harbor_repo/$project:$version
echo $imageName
containerId=`docker ps -a | grep ${project} | awk '{printf $l}'`
echo $containerId
if [ -z $containerId ];
then
echo "container doesn't exit"
else
docker stop $containerId
docker rm $containerId
fi
tag=`docker images | grep ${project} | grep ${version} | awk '{printf $2}'`
echo $tag
if [ -z $tag ];
then
echo "image doesn't exit"
else
docker rmi $imageName
fi
docker login -u admin -p Harbor12345 $harbor_addr
docker pull $imageName
docker run -d -p $host_port:$container_port --name $project $imageName
echo "SUCCESS"