pipeline { agent any parameters { gitParameter(name: 'BRANCH', type: 'PT_BRANCH', defaultValue: 'master', description: '选择 Git 分支') choice(name: 'ENV', choices: ['dev', 'staging', 'prod'], description: '选择部署环境') } environment {
//需要到系统凭证中配置git凭证 git_auth = "jenkins-pipeline" git_timeout = "120" git_url = "[email protected]:xxxxxxxx/xxxxxxxx.git" docker_url = "docker-hub.xxxxxx.com" docker_space = "xxxx" project_name = "xx-xx" docker_tag = "latest" } stages { stage('环境检测') { steps { script{ } sh label: '', script: ''' mvn -v git version java -version docker -v ''' } } stage('代码获取') { steps { checkout([ $class: 'GitSCM', branches: [[name: "${params.BRANCH}"]], extensions: [[ $class: 'CloneOption', noTags: false, reference: '', shallow: false, timeout: "${git_timeout}" ]], userRemoteConfigs: [[credentialsId: "${git_auth}", url: "${git_url}"]] ]) } } stage('项目构建') { steps { script { sh """ mvn clean package -Dmaven.test.skip=true """ } } } stage('构建镜像') { steps { script { // 使用 Dockerfile 构建镜像 sh """ docker build -t ${docker_url}/${docker_space}/${project_name}:${docker_tag} . """ } } } stage('镜像上传') { steps { script { // 登录到 Docker Hub // sh "echo '${DOCKER_HUB_PASSWORD}' | docker login -u '${DOCKER_HUB_USERNAME}' --password-stdin" // 推送镜像 sh """ docker push ${docker_url}/${docker_space}/${project_name}:${docker_tag} docker rmi ${docker_url}/${docker_space}/${project_name}:${docker_tag} """ } } } stage('发布') { steps { script { // 根据选择的部署环境设置相应的环境变量 if (params.DEPLOY_ENV == 'dev') { // 设置开发环境的环境变量 } else if (params.DEPLOY_ENV == 'staging') { // 设置预发布环境的环境变量 } else if (params.DEPLOY_ENV == 'production') { // 设置生产环境的环境变量 } // 目标服务器的 IP 列表 def target_servers = ['192.168.0.123'] // 使用循环遍历目标服务器列表 for (target_server_ip in target_servers) { echo "Deploying to server: ${target_server_ip}" // 在目标服务器上部署 Docker 容器(替换为目标服务器的用户名) // 确保目标服务器已经安装了 Docker,并且 Jenkins 有权限 SSH 访问目标服务器 sh """ ssh -o StrictHostKeyChecking=no root@${target_server_ip} ' set -x && docker pull ${docker_url}/${docker_space}/${project_name}:${docker_tag} && if docker ps -a | grep -w "${project_name}" >/dev/null; then docker stop ${project_name} && docker rm ${project_name} && docker rmi ${docker_url}/${docker_space}/${project_name}:${docker_tag} fi && docker run --init -d -m 512M -v /data:/data -e JVM_XMX=256M -e JVM_XMS=256M --net=host --name ${project_name} -d --restart always ${docker_url}/${docker_space}/${project_name}:${docker_tag} ' """ } } } } stage('清空工作目录') { steps { deleteDir() } } } post { always { sh label:'', script:""" """ } } }
标签:pipeline,git,name,url,project,steps,jenkins,docker From: https://www.cnblogs.com/bookc/p/17247165.html