Jenkins的agent用來指定跑構建的機器或Docker鏡像。因爲Docker擁有良好的隔離性,可以保證每次的構建是全新的。 以下面例子,經過agent {docker {image : 'xxx'}}
首先pull一個我打包好的基於ubuntu的node鏡像,這個鏡像裏面已經包含了nodejs10, wget, zip, curl, python,chrome,firefox, aws-cli 等經常使用工具,能夠方便的在裏面執行npm install,npm run test 啓動瀏覽器跑測試等。node
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
}
複製代碼
須要安裝 Jenkins docker workflow 插件, 下面的例子展現了:python
#!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),第二個參數是帳號密碼登陸憑證,須要提早建立
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()
// 能夠優化,用匹配搜索並刪除
sh "docker rmi fineyma/node-demo:${env.BUILD_NUMBER}-${git_commit}"
}
}
}
// clean workspace
cleanWs()
}
}
}
}
複製代碼
這裏 customImage.push() 貌似有個bug,構建以後的鏡像有兩個同樣的,一個帶registry name一個不帶git
關於 docker.build, docker.withRegistry 等是Jenkins docker workflow 插件提供的, 能夠看源碼,實際上是封裝了docker build, docker login,你徹底能夠寫原生的 docker 命令github
既然鏡像已經成功上傳到阿里雲的鏡像服務,理論上任何裝有Docker的主機只要docker run就能夠完成部署了(須要網絡通)。 實現方法我想到有幾種:web
docker run --rm fineyma/node-demo:${env.BUILD_NUMBER}-${git_commit}
step 步驟