我们的项目使用多阶段CI设置,第一阶段检查package-lock.json
和Gemfile.lock
等文件的修改,编译所有这些依赖项,然后将它们推送到Gitlab容器注册表。
在基于当前主线分支的Docker build中使用--cache-from
,这是相当快的,并且Docker分层机制有助于防止重复步骤。
随后的阶段和作业将使用第一阶段推送的Docker镜像作为其image:
。
为提高可读性而进行的缩写配置:
stages:
- create_builder_image
- test
Create Builder Image:
stage: create_builder_image
script:
- export DOCKER_BRANCH_TAG=$CI_COMMIT_REF_SLUG
# do stuff to build the image, using cache to speed it up
- docker push $GITLAB_IMAGE/builder:$DOCKER_BRANCH_TAG
Run Tests:
image: $GITLAB_IMAGE/builder:$CI_COMMIT_REF_SLUG
stage: test
script:
# do stuff in the context of the image build in the first stage
不幸的是,在处理运行时间更长的功能分支时,我们现在遇到的情况是,第二步中的映像有时看起来已经过时,并且在开始作业之前没有从注册表中提取最新版本,这使得后续作业抱怨缺少依赖项。
我可以做些什么来强制它总是为每个作业拉出最新的图像?
发布于 2021-10-29 12:10:56
正如已经在注释中所写的,我不会使用$CI_COMMIT_REF_SLUG
进行标记。原因很简单,因为不能保证所有管道都会以相同的顺序运行,而这本身就会产生问题。与您目前正在经历的情况相同。
我建议使用$CI_COMMIT_SHA
,因为它绑定到管道。我还将依靠以前的构建来进行缓存,我将很快在这里概述我的方法。
stages:
- create_builder_image
- test
- deploy
Create Builder Image:
stage: create_builder_image
script:
- (docker pull $GITLAB_IMAGE/builder:$CI_COMMIT_REF_SLUG && export DOCKER_CACHE_TAG=$CI_COMMIT_REF_SLUG) || (docker pull $GITLAB_IMAGE/builder:latest && export DOCKER_CACHE_TAG=latest) || true
- docker build --cache-from $GITLAB_IMAGE/builder:$DOCKER_CACHE_TAG ...
# do stuff to build the image, using cache to speed it up
- docker push $GITLAB_IMAGE/builder:$CI_COMMIT_SHA
Run Tests:
image: $GITLAB_IMAGE/builder:$CI_COMMIT_SHA
stage: test
script:
# do stuff in the context of the image build in the first stage
Push image: # pushing the image for the current branch ref, as i know it is a working image and it can than be used for caching by others.
image: docker:20
stage: deploy
variables:
GIT_STRATEGY: none
stage: push
script:
- docker pull $GITLAB_IMAGE/builder:$CI_COMMIT_SHA
- docker tag $GITLAB_IMAGE/builder:$CI_COMMIT_SHA $GITLAB_IMAGE/builder:$CI_COMMIT_REF_SLUG
- docker push $GITLAB_IMAGE/builder:$CI_COMMIT_REF_SLUG
我知道它可能会生成额外的构建步骤,但通过这种方式,您可以确保始终拥有属于管道的映像。您仍然可以从docker使用缓存和分层,如果测试失败,当前将不会推送镜像。
此外,您还可以在创建构建映像之前创建一个步骤,以便确定是否确实需要一个新映像。
https://stackoverflow.com/questions/69766587
复制相似问题