工具与资源中心
帮助开发者更加高效的工作 提供围绕开发者全生命周期的工具与资源
背景kaniko是一款方便我们从K8S内部构建docker容器的工具 以前我们在CI过程中 使用的是docker-in-docker技术 这种技术最主要的缺陷就是当一台机器上同时运行多个docker build流水线时 会出现阻塞的情况 因为这一批流水线用的是宿主机上的同一个docker进程。
基于这种情况 我们在droneCI流水线中换用了kaniko来进行docker镜像的创建。
遇到的难题 kaniko是基于scratch构建的 里面没有shell 所以想在kaniko原生镜像里在调用python是很麻烦的kaniko创建docker镜像使用的是file system功能 如果想在一个kaniko容器里先创建ubuntu镜像 再创建alpine镜像 是会有各种冲突问题的 需要使用–cleanup功能。此功能会清空文件系统 同时如果有自己装的shell,也会被清空 导致无法再次使用 解决方案 kaniko的关键文件其实是/kaniko目录下的哪些 二进制文件 官方推荐是用gcr.io/kaniko-project/executor 镜像 其实我们可以拷贝这个/kaniko目录到我们自己的私有镜像shell没有的话 我们可以拷贝一个busybox进去 这样就有shell了虽然–cleanup会清空file system 但是根据代码里的ignorepath设定 volume挂载目录和/kaniko目录会被忽略掉。所以我们可以有两种方式选择 一、通过volume的方式哦挂载busybox和自己的python代码到私有镜像里。二、把busybox和python代码加入/kaniko目录。 示例代码Dockerfile如下
FROM heiheidoc/kaniko-project-executor:v1.3.0 AS plugin # 1.6.0的clean up有问题 https://github.com/GoogleContainerTools/kaniko/issues/1586 FROM heiheidoc/kaniko-project-executor:debug AS debug FROM python:3.9.5-buster COPY --from 背景plugin /kaniko /kaniko COPY --from debug /busybox /kaniko/busybox ADD . /kaniko ENV DOCKER_ConFIG /kaniko/.docker CMD [ python3 , /kaniko/main.py ]
部分python代码如下 功能是按照一定规则生成Docker镜像
def run_shell(shell): print_green(shell) cmd subprocess.Popen(shell, stdin subprocess.PIPE, stderr sys.stderr, close_fds True, stdout sys.stdout, universal_newlines True, shell True,executable /kaniko/busybox/sh , bufsize 1) cmd.communicate() return cmd.returncode def run_executor(): for folder_name, sub_dir, files in os.walk(os.getcwd()): if Dockerfile in files: Dockefile_path folder_name /Dockerfile docker_info folder_name.replace(os.getcwd(), ).split( / ) harbor_image_name REGISTRY_URL / owner_name / docker_info[1] : docker_info[2] cmd_build /kaniko/executor --cache true --cache-dir /cache --cleanup --skip-tls-verify --skip-tls-verify-pull --skip-tls-verify-registry --dockerfile Dockefile_path --context dir:// folder_name --destination harbor_image_name assert run_shell(cmd_build) 0, 镜像build失败: harbor_image_name if __name__ __main__ : run_executor()



