CI/CD:这次怎么落地的

这次 CI/CD 平台从 Jenkins 迁移到 GitLab CI/CD,中间踩了一些坑,但也理解了自动化部署的价值。

最初的部署是手工的:本地打包,上传到服务器,解压,重启服务。

最初的 Jenkins 时代

最初的部署是手工的:本地打包,上传到服务器,解压,重启服务。

# 部署流程
cd project
npm run build
tar -czf build.tar.gz dist
scp build.tar.gz user@server:/var/www/
ssh user@server "cd /var/www && tar -xzf build.tar.gz && pm2 restart myapp"

后来上了 Jenkins,但维护成本不低:

  • 需要维护 Jenkins 服务器
  • 插件生态复杂,升级经常出问题
  • 配置文件多,不容易管理

GitLab CI/CD 的优势

GitLab CI/CD 是代码仓库原生的 CI/CD 工具,用起来更简单。

基础配置

# .gitlab-ci.yml
stages:
  - test
  - build
  - deploy

test:
  stage: test
  script:
    - npm ci
    - npm run test

build:
  stage: build
  script:
    - npm run build
  artifacts:
    paths:
      - dist/

deploy:
  stage: deploy
  script:
    - scp -r dist/* user@server:/var/www/
    - ssh user@server "cd /var/www && pm2 restart myapp"
  only:
    - main

GitLab 检测到代码提交后,自动执行流水线。

多环境配置

stages:
  - deploy
  - deploy:staging
  - deploy:production

deploy:staging:
  stage: deploy:staging
  script:
    - echo "Deploying to staging"
  environment:
    name: staging
    url: https://staging.example.com

deploy:production:
  stage: deploy:production
  script:
    - echo "Deploying to production"
  environment:
    name: production
    url: https://example.com
  when: manual

生产环境部署需要手动确认。

构建优化

缓存机制

GitLab CI/CD 支持构建缓存,加快构建速度。

variables:
  NODE_ENV: production
  CACHE_KEY: ${CI_COMMIT_REF_SLUG}

cache:
  paths:
    - node_modules/

before_script:
  - npm ci

并行构建

多个 job 并行执行,缩短整体时间。

stages:
  - test
  - build
  - deploy

test:unit:
  stage: test
  script:
    - npm run test:unit

test:e2e:
  stage: test
  script:
    - npm run test:e2e
  needs:
    - test:unit

安全实践

Secret 管理

敏感信息不能明文写在配置文件里。

# 在 GitLab UI 中配置 CI/CD 变量
deploy:
  stage: deploy
  script:
    - echo "$DB_PASSWORD" | kubectl create secret generic db-secret --dry-run=client -f -
  variables:
    DB_PASSWORD: ${DB_PASSWORD}

环境变量

stages:
  - deploy

deploy:staging:
  stage: deploy
  variables:
    ENVIRONMENT: staging
  script:
    - echo "Deploying to $ENVIRONMENT"

踩过的坑

坑一:构建失败但缓存还保留

某次构建失败,但缓存被保存了,下次构建用到了错误的缓存。

解决:在失败时清除缓存。

cache:
  key: ${CI_COMMIT_REF_SLUG}
  paths:
    - node_modules/
  policy: pull-push

坑二:脚本权限问题

脚本在 Runner 上执行时权限不对,导致部署失败。

解决:在脚本中设置正确的权限。

deploy:
  stage: deploy
  script:
    - chmod +x deploy.sh
    - ./deploy.sh

坑三:依赖下载慢

国内访问 npm 源慢,构建时间过长。

解决:使用淘宝镜像。

before_script:
  - npm config set registry https://registry.npmmirror.com

什么时候需要 CI/CD

CI/CD 适合任何需要自动化部署的场景。

必须用的场景

  • 多人协作,需要统一部署流程
  • 需要频繁部署
  • 需要回滚能力

可以暂缓的场景

  • 个人项目,部署不频繁
  • 团队规模小,手动部署可接受

写在最后

CI/CD 这东西,不是技术问题,是流程问题。

它解决了"谁来部署、怎么部署、什么时候部署"这些基本问题。但对于团队协作和运维效率的提升是明显的。

GitLab CI/CD 相比 Jenkins 的优势在于:

  • 原生集成
  • 配置简单
  • 维护成本低

选型的时候,不要只看技术指标,还要看团队能力和维护成本。


这次 CI/CD 迁移之后,部署从 30 分钟缩短到 5 分钟,而且再也不担心部署出错了。自动化部署的价值确实很大。

版权声明: 本文首发于 指尖魔法屋-CI/CD:这次怎么落地的https://blog.thinkmoon.cn/post/57-cicd-practice-jenkins-gitlab/) 转载或引用必须申明原指尖魔法屋来源及源地址!