pipeline { agent any tools { maven 'Maven 3.9.2' } stages { stage('拉取代码') { steps { git branch: 'main', credentialsId: 'chatx', url: 'git路径' echo '拉取成功' } } stage('执行构建') { steps { echo '开始构建...' sh "mvn --version" sh "cd /var/lib/jenkins/workspace/chatx-test/项目路径" sh "mvn package -Dmaven.test.skip=true" echo '构建完成' } } stage('备份并替换 jar 包') { steps { script { def jarFile = 'jar包路径' def targetPath = '/work/projects/yudao-server/镜像路径' def targetPathBf = '/work/projects/yudao-server/备份路径/' def timestamp = sh(script: 'date +%F_%T', returnStdout: true).trim() def backupPath = "${targetPathBf}${timestamp}/" echo "备份路径: ${backupPath}" // 创建备份目录 sh """ set -e mkdir -p ${backupPath} """ // 备份现有的 jar 包(如果存在) sh """ if [ -f ${targetPath}yudao-server.jar ]; then cp ${targetPath}yudao-server.jar ${backupPath}/ echo '现有的 jar 包已备份到 ${backupPath}' else echo '没有找到现有的 jar 包,跳过备份' fi """ // 替换 jar 包为新的构建产物 sh """ cp ${jarFile} ${targetPath}/ echo '新的 jar 包已替换到目标路径' """ } } } stage('构建 Docker 镜像并运行') { steps { script { def imageName = 'yudao-server-image' def containerName = 'yudao-server-container' // 构建 Docker 镜像 echo '正在构建 Docker 镜像...' sh """ docker build -t ${imageName} -f /var/lib/jenkins/workspace/chatx-test/yudao-server/Dockerfile /var/lib/jenkins/workspace/chatx-test/yudao-server/ """ // 停止并删除现有 Docker 容器(如果存在) echo '正在停止并删除现有的 Docker 容器...' sh """ docker rm -f ${containerName} || true """ // 运行新的 Docker 容器 echo '正在运行新的 Docker 容器...' sh """ docker run --name ${containerName} -d -p 8080:8080 ${imageName} """ } } } } }
标签:脚本,yudao,配置,jar,echo,sh,jenkins,Docker,server From: https://www.cnblogs.com/aknife/p/18365445