GitLab CI/CD 最佳实践:从入门到生产级流水线

GitLab CI/CDDevOps 工具链的核心组件。本文将分享 GitLab CI/CD 的最佳实践。

一、流水线结构设计

stages:
  - lint
  - test
  - build
  - deploy

variables:
  DOCKER_IMAGE: $CI_REGISTRY_IMAGE:$CI_COMMIT_SHORT_SHA

lint:
  stage: lint
  image: node:20
  script:
    - npm ci
    - npm run lint

test:
  stage: test
  image: node:20
  script:
    - npm ci
    - npm run test:ci
  coverage: '/Lines\s*:\s*(\d+\.\d+%)/'

二、缓存策略

cache:
  key: $CI_COMMIT_REF_SLUG
  paths:
    - node_modules/
    - .npm/
  policy: pull-push

三、多环境部署

deploy-review:
  stage: deploy
  only:
    - merge_requests
  environment:
    name: review/$CI_MERGE_REQUEST_IID
    url: https://$CI_MERGE_REQUEST_IID.example.com
  script:
    - ./deploy-review.sh

deploy-production:
  stage: deploy
  only:
    - main
  when: manual
  environment:
    name: production
    url: https://example.com
  script:
    - ./deploy.sh

四、安全扫描

include:
  - template: Jobs/SAST.gitlab-ci.yml
  - template: Jobs/Dependency-Scanning.gitlab-ci.yml
  - template: Jobs/Secret-Detection.gitlab-ci.yml