Gitlab CI:如何从预构建图像缓存 node_modules?

Gitlab CI : how to cache node_modules from a prebuilt image?

情况是这样的: 我是 运行 Gitlab CI 中的 Cypress 测试(由 vue-cli 启动)。为了加快执行速度,我构建了一个包含必要依赖项的 Docker 映像。 如何从预构建图像中缓存 node_modules 以在测试作业中使用它? 目前我正在使用一个糟糕(但有效)的解决方案:

testsE2e:
  image: path/to/prebuiltImg
  stage: tests
  script:
    - ln -s /node_modules/ /builds/path/to/prebuiltImg/node_modules
    - yarn test:e2e
    - yarn test:e2e:report

但我认为必须有更清洁的方式使用 Gitlab CI 缓存。

我一直在测试:

cacheE2eDeps:
  image: path/to/prebuiltImg
  stage: dependencies
  cache:
    key: e2eDeps
    paths:
      - node_modules/
  script:
    - find / -name node_modules # check that node_modules files are there
    - echo "Caching e2e test dependencies"

testsE2e:
  image: path/to/prebuiltImg
  stage: tests
  cache:
    key: e2eDeps
  script:
    - yarn test:e2e
    - yarn test:e2e:report

但是作业缓存 E2eDeps 显示 "WARNING: node_modules/: no matching files" 错误。 我怎样才能成功做到这一点? Gitlab 文档并没有真正谈论从预构建图像缓存...

用于构建映像的Docker文件:

FROM cypress/browsers:node13.8.0-chrome81-ff75

COPY . .
RUN yarn install

没有关于从预构建图像中缓存数据的文档,因为它根本没有完成。依赖项在映像中已经可用,那么为什么要首先缓存它们呢?这只会导致不必要的数据重复。

此外,您似乎在缓存应该用于在作业之间共享数据的印象下操作,但它的主要用例是在同一作业的不同 运行 之间共享数据。应使用工件在作业之间共享数据。

在您的情况下,您可以使用缓存而不是预构建图像,如下所示:

variables:
  CYPRESS_CACHE_FOLDER: "$CI_PROJECT_DIR/cache/Cypress"

testsE2e:
  image: cypress/browsers:node13.8.0-chrome81-ff75
  stage: tests
  cache:
    key: "e2eDeps"
    paths:
      - node_modules/
      - cache/Cypress/
  script:
    - yarn install
    - yarn test:e2e
    - yarn test:e2e:report

上面的作业第一次是 运行,它会从头开始安装依赖项,但下一次它会从 运行ner 缓存中获取它们。需要注意的是,除非 运行 这个作业的所有 运行 用户共享缓存,否则每次你 运行 它在一个新的 运行 用户上它都会从头开始安装依赖项。

这是关于在 GitLab CI 中使用纱线的 documentation

编辑:

详细说明使用缓存与工件 - 工件既用于存储作业输出(例如,稍后手动下载),也用于将一个作业的结果从后续阶段传递给另一个作业,而缓存用于通过保留作业需要从 Internet 下载的文件来加快作业执行速度。有关详细信息,请参阅 GitLab documentation

node_modules 目录的内容显然属于第二类。