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 步骤