You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

GitLab CI Runner构建Nx Monorepo应用遇缓存与Docker问题求助

GitLab CI配置修复:缓存优化与Docker构建问题解决

一、缓存失效问题修复

当前缓存不生效的核心原因:

  1. 缓存路径未覆盖yarn实际缓存目录(配置了--cache-folder .yarn-cache但缓存路径未包含该目录)
  2. before_script中强制执行yarn install,未利用缓存跳过不必要的安装
  3. 同时使用cache和artifacts传递node_modules,逻辑冗余且可能冲突

修复步骤:

  • 调整缓存路径,包含.yarn-cache、node_modules和.yarn
  • 为yarn install添加--prefer-offline参数,优先使用本地缓存
  • 移除artifacts中node_modules的配置,改用cache实现跨job依赖共享
  • 明确缓存策略为pull-push,确保job先拉取缓存、安装后推送更新

二、Docker构建失败问题修复

Docker-in-Docker(DinD)构建失败的常见问题:

  1. 未配置Docker环境变量,导致客户端无法连接到守护进程
  2. 未获取到build阶段生成的dist文件
  3. DinD服务未启用特权模式,权限不足
  4. 触发规则不够精准,无用构建导致资源浪费

修复步骤:

  • 为Docker构建job添加对应环境变量,适配DinD服务
  • 给build阶段添加artifacts传递dist目录到后续阶段
  • 启用DinD服务的特权模式
  • 用changes规则精准匹配修改的应用文件,仅在必要时触发构建

完整修复后的CI配置

default:
  image: registry.gitlab.com/xxxx/xxxx/xxxx

stages:
  - test
  - build
  - forge

.distributed:
  interruptible: true
  only:
    - main
    - develop
  cache:
    key:
      files:
        - yarn.lock
    paths:
      - node_modules
      - .yarn-cache
      - .yarn
    policy: pull-push
  before_script:
    - yarn install --cache-folder .yarn-cache --immutable --immutable-cache --check-cache --prefer-offline
    - NX_HEAD=$CI_COMMIT_SHA
    - NX_BASE=${CI_MERGE_REQUEST_DIFF_BASE_SHA:-$CI_COMMIT_BEFORE_SHA}

test:
  stage: test
  extends: .distributed
  script:
    - yarn nx affected --base=$NX_BASE --head=$NX_HEAD --target=test --parallel=3 --ci --code-coverage

build:
  stage: build
  extends: .distributed
  script:
    - yarn nx affected --base=$NX_BASE --head=$NX_HEAD --target=build --parallel=3
  artifacts:
    paths:
      - dist/apps/
    expire_in: 1h

forge-docker-landing-staging:
  stage: forge
  image: docker:20.10.16
  services:
    - name: docker:20.10.16-dind
      privileged: true
  variables:
    DOCKER_HOST: tcp://docker:2375
    DOCKER_TLS_CERTDIR: ""
  rules:
    - if: $CI_COMMIT_BRANCH == "develop"
      changes:
        - apps/landing/**/*
        - Dockerfile.landing
      allow_failure: false
  script: 
    - docker build -f Dockerfile.landing -t landing:staging .
    # 可选:添加镜像推送逻辑
    # - docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY
    # - docker tag landing:staging $CI_REGISTRY_IMAGE/landing:staging
    # - docker push $CI_REGISTRY_IMAGE/landing:staging

关键说明

  • 缓存:通过policy: pull-push和--prefer-offline大幅减少重复安装时间
  • NX affected:保持原有逻辑,仅处理修改过的应用,提升CI效率
  • Docker构建:通过changes规则精准触发,避免无效构建;关闭TLS为简化调试,生产环境建议启用TLS并配置对应证书变量
  • artifacts:仅传递必要的dist/apps/目录,设置有效期减少存储占用

内容的提问来源于stack exchange,提问作者antonyftp

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 02:41:59