GitLab CI/CD本地包含多子项目时部分缓存失效问题求助
解决GitLab CI/CD Monorepo多流水线缓存冲突问题
问题分析
你当前的缓存配置使用统一的$CI_COMMIT_REF_SLUG作为key,当两个子项目的流水线同时运行时,会出现缓存竞争覆盖:比如frontend的构建Job先完成并更新缓存,直接覆盖了infrastructure之前写入的缓存内容,导致后续infrastructure的Job读取不到正确的缓存;而单独运行时无竞争,所以缓存正常工作。
解决方案
1. 为不同子项目设置独立缓存Key
给每个子项目的缓存绑定专属Key,彻底避免不同子项目共享同一个缓存实例,有两种实现方式:
方式一:根目录定义缓存模板
# 根目录 gitlab-ci.yml # 定义基础设施项目缓存模板 .cache_infrastructure: cache: key: "$CI_COMMIT_REF_SLUG-infrastructure" paths: - infrastructure/node_modules/ - infrastructure/dist/ # 定义前端项目缓存模板 .cache_frontend: cache: key: "$CI_COMMIT_REF_SLUG-frontend" paths: - frontend/node_modules/ - frontend/dist/ include: - local: '/infrastructure/infrastructure.gitlab-ci.yml' rules: - changes: - 'infrastructure/*' - local: '/frontend/frontend.gitlab-ci.yml' rules: - changes: - 'frontend/*'
然后在子项目CI文件中引用对应模板:
# infrastructure/infrastructure.gitlab-ci.yml build_infrastructure: extends: .cache_infrastructure script: - cd infrastructure - npm install - npm run build
方式二:子项目CI文件直接定义缓存
# infrastructure/infrastructure.gitlab-ci.yml cache: key: "$CI_COMMIT_REF_SLUG-infrastructure" paths: - infrastructure/node_modules/ - infrastructure/dist/ build_infrastructure: script: - cd infrastructure - npm install - npm run build
# frontend/frontend.gitlab-ci.yml cache: key: "$CI_COMMIT_REF_SLUG-frontend" paths: - frontend/node_modules/ - frontend/dist/ build_frontend: script: - cd frontend - npm install - npm run build
2. 限制缓存路径范围
确保每个子项目的缓存仅包含自身目录下的文件,不要同时覆盖多个子项目路径,进一步降低缓存干扰风险。
3. 子项目Job串行执行(可选)
如果GitLab Runner并发数较高,可给子项目Job添加resource_group,确保同一子项目的Job串行执行,避免子项目内部也出现缓存竞争:
# infrastructure/infrastructure.gitlab-ci.yml build_infrastructure: cache: key: "$CI_COMMIT_REF_SLUG-infrastructure" paths: - infrastructure/node_modules/ - infrastructure/dist/ resource_group: infrastructure-group script: - cd infrastructure - npm install - npm run build
内容的提问来源于stack exchange,提问作者Duba
相关产品推荐
相关产品推荐

