个人亲自录制全套DevOps系列实战教程 :手把手教你玩转DevOps全栈技术
Jenkinsfile中可以直接调用docker,比如构建一个镜像、推送镜像、启动容器等,都可以在agent指令中使用,
此时表示通过jenkins节点来运行docker容器,即docker容器作为执行Jenkinsfile的代理机器,也就是说jenkinsfile的阶段会交给docker容器去执行。[注意理解]
这和我们之前的案例,由jenkins来构建镜像并推送镜像是有区别的,此处启动的docker容器主要作用是运行jenkinsfile的step步骤,当然我们也可以让该容器通过执行step去完成我们之前案例中的构建镜像、推送镜像的功能
前提:需要安装Docker Pipeline插件,否则agent中指定docker是无法被识别为代理节点的
pipeline {
agent {
// 让jenkins节点调用本地的docker服务(比如之前我们映射的docker宿主机的docker服务)去启动一个容器
// 去执行Jenkinsfile后边的stages阶段,即在容器内部执行node --version
docker { image 'node:7-alpine' }
}
stages {
stage('Test') {
steps {
sh 'node --version'
}
}
}
}
构建完成后会删除容器:日志如下
Started by user admin标签:node,容器,Pipeline,--,DevOps,jenkins,docker,Docker,Jenkinsfile From: https://blog.51cto.com/u_15909716/5996691
Replayed #15
[Pipeline] Start of Pipeline
[Pipeline] node
Running on Jenkins in /var/jenkins_home/workspace/p1
[Pipeline] {
[Pipeline] isUnix
[Pipeline] withEnv
[Pipeline] {
[Pipeline] sh
+ docker inspect -f . node:7-alpine
.
[Pipeline] }
[Pipeline] // withEnv
[Pipeline] withDockerContainer
Jenkins seems to be running inside container babd00931aa08fa1bdfeaf62ec3fbccc4c7a32f285973a3339cb3f3a56d3413f
$ docker run -t -d -u 1000:1000 -w /var/jenkins_home/workspace/p1 --volumes-from babd00931aa08fa1bdfeaf62ec3fbccc4c7a32f285973a3339cb3f3a56d3413f -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** node:7-alpine cat
$ docker top 0f98c57f3079ecd6606c4d3b81d365f57a11ce2feea406b88ac17f393e568446 -eo pid,comm
[Pipeline] {
[Pipeline] stage
[Pipeline] { (Test)
[Pipeline] sh
+ node --version
v7.10.1
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
$ docker stop --time=1 0f98c57f3079ecd6606c4d3b81d365f57a11ce2feea406b88ac17f393e568446
$ docker rm -f --volumes 0f98c57f3079ecd6606c4d3b81d365f57a11ce2feea406b88ac17f393e568446
[Pipeline] // withDockerContainer
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS