TODO 待補充流程圖
構建任務在指定Docker鏡像中進行
如下面例子捆等,首先pull一個我打包好的基于ubuntu的node鏡像移剪,這個鏡像里面已經包含了nodejs10, wget, zip, curl, python叉庐,chrome,firefox, aws-cli 等常用工具副瀑,可以方便的在里面執(zhí)行npm install想幻,npm run test 啟動瀏覽器跑測試等。
pipeline {
agent {
docker {
image 'finleyma/circleci-nodejs-browser-awscli'
}
}
stage('Checkout') {
steps {
git branch: 'develop', credentialsId: 'github-private-key', url: 'git@github.com:your-name/angular-web.git'
}
}
stage('Node modules') {
steps {
sh 'npm install'
}
}
stage('Code Lint') {
steps {
sh 'npm run lint'
}
}
stage('Unit Test') {
steps {
sh 'npm run test'
}
}
// .... build, delpoy
}
pipeline 中操作鏡像
需要安裝 Jenkins docker workflow 插件,
下面的例子展示了:
- 連接遠程Docker主機
- 登錄私有Docker 倉庫(阿里云鏡像服務)
- 根據代碼中的 Dockerfile 構建鏡像并push
- 刪除Docker遠程主機中構建好的鏡像弥虐,不占用空間
- 不包含目標主機中部署鏡像
其實就說上篇文章中的pipeline版本
#!groovy
pipeline {
agent any
environment {
// PATH="/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin"
_docker_remote_server='tcp://192.100.155.155:2375'
_aliyun_registry='https://registry.cn-zhangjiakou.aliyuncs.com'
}
stages {
stage('debug') {
steps {
script {
sh "printenv"
}
}
}
stage('connect remote docker') {
steps {
// 注意 代碼是先拉到了Jenkins主機上扩灯,但是構建鏡像在Docker遠程
git 'https://github.com/mafeifan/docker-express-demo.git'
script {
docker.withServer("${env._docker_remote_server}") {
// 第一個參數是私有倉庫地址,注意要帶http(s)霜瘪,第二個參數是賬號密碼登錄憑證珠插,需要提前創(chuàng)建
docker.withRegistry("${env._aliyun_registry}", 'aliyun-docker-registry') {
// 使用 ${GIT_PREVIOUS_COMMIT} 取不到 commint_id
// https://stackoverflow.com/questions/35554983/git-variables-in-jenkins-workflow-plugin
git_commit = sh(returnStdout: true, script: "git rev-parse HEAD").trim()
echo git_commit
def customImage = docker.build("fineyma/node-demo:${env.BUILD_NUMBER}-${git_commit}")
/* Push the container to the custom Registry */
customImage.push()
// 可以優(yōu)化,用匹配搜索并刪除
sh "docker rmi fineyma/node-demo:${env.BUILD_NUMBER}-${git_commit}"
}
}
}
// clean workspace
cleanWs()
}
}
}
}
這里 customImage.push() 貌似有個bug颖对,構建之后的鏡像有兩個一樣的捻撑,一個帶registry name一個不帶
關于 docker.build, docker.withRegistry 等是Jenkins docker workflow 插件提供的, 可以看源碼,其實是封裝了docker build, docker login缤底,你完全可以寫原生的docker 命令
關于遠程容器部署
既然鏡像已經成功上傳到阿里云的鏡像服務顾患,理論上任何裝有Docker的主機只要docker run就可以完成部署了(需要網絡通)。
實現(xiàn)方法我想到有幾種:
- 阿里云的鏡像服務提供觸發(fā)器个唧,即每當push新的鏡像上去描验,可以發(fā)送一個post請求到配置的地址,這樣可以完成容器部署操作坑鱼。Jenkins可以添加一個job膘流,暴露一個觸發(fā)地址給阿里云鏡像服務的觸發(fā)器。
- 在pipeline中添加ssh登錄目標主機鲁沥,然后添加
docker run --rm fineyma/node-demo:${env.BUILD_NUMBER}-${git_commit}
step 步驟 - 目標主機也開放dockerd呼股,這樣連登錄都不需要了,直接docker client 操作遠程Docker完成部署画恰。
參考
https://jenkins.io/doc/pipeline/steps/docker-workflow
https://jenkins.io/doc/book/pipeline/docker