前言
前一篇文章【云原生之旅 - 11)基于 Kubernetes 动态伸缩 Jenkins Build Agents】有讲到在 Kubernetes Pod (Jenkins build agent) 里面构建 docker 容器镜像,当时我们采取了一种简单快速的方式来 run docker in docker,也就是 mount /var/run/docker.sock 到主机的 docker engine,这需要docker run在特权 privileged 模式下,有很大的安全隐患。另外这种方式还有个很大的缺陷就是当一台机器上同时运行多个docker build agent时,会出现阻塞的情况,因为这一批agent用的都是宿主机上的同一个docker engine。
原理
准备
kubectl -n jenkins create secret docker-registry dockercred \ --docker-server=https://index.docker.io/v1/ \ --docker-username=<dockerhub-username> \ --docker-password=<dockerhub-password>
使用 Kaniko 构建镜像
Define kaniko container in Pod Template
并且挂载刚才建的 docker-registry类型的secret
kind: Pod spec: containers: # list of containers that you want present for your build, you can define a default container in the Jenkinsfile - name: kaniko image: gcr.io/kaniko-project/executor:v1.9.0-debug # include shell imagePullPolicy: IfNotPresent command: - /busybox/cat tty: true resources: limits: cpu: 500m memory: 1024Mi volumeMounts: - name: kaniko-secret mountPath: /kaniko/.docker volumes: - name: kaniko-secret secret: secretName: dockercred items: - key: .dockerconfigjson path: config.json
Jenkins pipeline
- --context: This is the location of the Dockerfile.
- --destination: You need to replace Docker Hub username `wadexu007` with your Docker Hub username for kaniko to push the image to the Docker Hub registry.
pipeline { options { timeout(time: 10, unit: 'MINUTES') buildDiscarder(logRotator(numToKeepStr: '10', daysToKeepStr: '7')) } agent { kubernetes { idleMinutes 3 // how long the pod will live after no jobs have run on it yamlFile 'Jenkins/kaniko-demo/build-pod.yaml' // path to the pod definition relative to the root of our project } }
stages { stage('Kaniko Build and Push Docker Image') { steps { script { dir('Jenkins/kaniko-demo') { container('kaniko') { sh """ /kaniko/executor --context `pwd` --destination wadexu007/demo-app:1.0.5 """ } } } } } } }
完整例子参考我的 Github Repo
### 本文同步发表于知乎 https://zhuanlan.zhihu.com/p/584805862
测试
创建一个Pipeline job
Repository URL = https://github.com/wadexu007/learning_by_doing
Script Path = Jenkins/kaniko-demo/Jenkinsfile
Click `Build now`
感谢阅读,如果您觉得本文的内容对您的学习有所帮助,您可以打赏和推荐,您的鼓励是我创作的动力
### 本文同步发表于知乎 https://zhuanlan.zhihu.com/p/584805862