Jenkins远程构建docker部署
时间: 2025-03-26 11:49:35 浏览: 36
### Jenkins 远程触发 Docker 构建与部署
#### 配置 GitLab Webhook 实现自动触发 Jenkins
为了使 Jenkins 能够实时响应来自 GitLab 的变更事件,需设置 GitLab 中项目的 Webhooks。具体操作是在 GitLab 项目设置中的 Integrations 页面添加一个新的 Webhook URL,该URL指向 Jenkins 接收通知的服务端点[^2]。
#### 设置 Jenkins Pipeline 执行远程 Docker 主机上的命令
在 Jenkinsfile 或者 Jenkins UI 中定义 pipeline 步骤时,可以利用 `ssh` 插件或者其他方式连接至远程 Docker 主机执行必要的构建指令:
```groovy
pipeline {
agent any
stages {
stage('Build') {
steps {
script {
sh '''
ssh user@remote-docker-host "sudo docker build -t my-app ."
'''
}
}
}
stage('Push Image to Harbor') {
steps {
script {
withCredentials([string(credentialsId: 'harbor-password', variable: 'HARBOR_PASSWORD')]) {
sh """
echo ${HARBOR_PASSWORD} | sudo docker login harbor.example.com --username admin --password-stdin
sudo docker tag my-app harbor.example.com/project/my-app:${BUILD_NUMBER}
sudo docker push harbor.example.com/project/my-app:${BUILD_NUMBER}
"""
}
}
}
}
// 更多阶段...
}
post { ... } // 清理工作区等后续处理逻辑
}
```
上述脚本展示了如何通过 SSH 命令让远程服务器运行 Docker 构建过程,并推送生成的镜像到私有仓库(如Harbor)。注意替换其中的具体参数以匹配实际环境配置[^3]。
#### 自动化测试和部署流程
一旦完成了以上两步的基础搭建之后,在每次向 GitLab 提交代码更新后,都会自动触发展开一系列动作——从源码拉取、编译打包直到最终发布新版本的应用程序实例。整个 CI/CD 流水线不仅提高了开发效率还减少了人为错误的可能性[^1]。
阅读全文
相关推荐


















