首页 > 解决方案 > gitlab runner - 如何缓存图像而不是每次都构建?

问题描述

我已经设置了 gitlab runner 来利用docker/compose:latest图像来运行一组服务。

通过设置图像被缓存而不是每次都被拉取 pull_policy="if-not-present"config.tomldocker/compose:latest

如何将测试阶段使用的 docker 服务设置为使用缓存的图像(即开始使用的图像docker-compose up -d)?我对这项dind服务有点困惑。

.gitlab-ci.yml

variables:
  DOCKER_HOST: tcp://docker:2375
  DOCKER_TLS_CERTDIR: ""
  DOCKER_DRIVER: overlay2
  CI_REGISTRY: my-docker-registry.local:5000

image:
  name: docker/compose:latest

services:
  - name: docker:dind
    command: ["--insecure-registry=my-docker-registry.local:5000"]

test:
  stage: test
  script:
    - docker-compose up -d

/etc/gitlab-runner/config.toml如下:

                                                   concurrent = 1
check_interval = 0

[[runners]]
  name = "user1"
  url = "http://gitlab.example.local/"
  token = "<MYTOKEN>"
  executor = "docker"
  [runners.docker]
    extra_hosts = ["my-docker-registry.local:192.168.1.100"]
    tls_verify = false
    tls_verify = false
    image = "docker:latest"
    privileged = true
    disable_cache = false
    pull_policy="if-not-present"
    volumes = ["/certs/client", "/cache"]    
    disable_entrypoint_overwrite = false
    oom_kill_disable = false
    shm_size = 0
  [runners.cache]

标签: docker-composegitlabgitlab-ci-runner

解决方案


仅适用于跑步者自己拉取pull_policy的图像。image:您在键(或services[]:name)中设置的 IE 图像。

如果您在使用docker docker执行器时在作业中使用(例如,在您使用docker-compose up -d的地方),那么您将无法利用缓存层,并且必须先从注册表中提取图像或从头开始构建。

原因是 docker-in-docker GitLab 作业使用该docker:dind服务作为其 docker 守护进程。该服务每次都会提供一个新的状态,因此不会利用缓存的图像,即使运行器本身已经缓存了图像。

但是,您可以从注册表中提取图像,并--cache-from使用docker build.

script:
    - docker pull $CI_REGISTRY_IMAGE:latest || true
    - docker build --cache-from $CI_REGISTRY_IMAGE:latest --tag $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA --tag $CI_REGISTRY_IMAGE:latest .

当然,您仍然必须每次都拉取镜像,但这可能比构建更快,特别是如果您的镜像安装了许多依赖项或编译大型模块或类似的东西。

有关更多信息,请参阅文档中的docker-in-docker部分。


推荐阅读