GitLab CI/CD流水线深度实践 (2026年03月27日) GitLab CI/CD概述 GitLab CI/CD是GitLab内置的持续集成、持续交付和持续部署工具,通过.gitlab-ci.yml配置文件定义流水线,实现代码提交后的自动化构建、测试和部署流程。 基础配置文件结构 关键概念 Jobs(任务) Job是CI/CD流程的基本执行单元,包含脚本和规则。 Stages(阶段) Stage定义Job的执行顺序,同一Stage的Job并行执行。 Pipeline(流水线) Pipeline由多个Stage组成,代表完整的CI/CD流程。 Environments(环境) 定义部署环境(dev、staging、production),支持环境回滚。
GitLab CI/CD是GitLab内置的持续集成、持续交付和持续部署工具,通过.gitlab-ci.yml配置文件定义流水线,实现代码提交后的自动化构建、测试和部署流程。
# .gitlab-ci.yml stages: - build - test - deploy variables: DOCKER_DRIVER: overlay2 IMAGE_NAME: myapp:$CI_COMMIT_SHORT_SHA build: stage: build script: - docker build -t $IMAGE_NAME . - docker push $IMAGE_NAME only: - main - develop test: stage: test script: - npm run test - npm run lint coverage: '/Code coverage: \d+\.\d+/' deploy_staging: stage: deploy script: - kubectl set image deployment/myapp myapp=$IMAGE_NAME -n staging environment: name: staging url: https://staging.example.com only: - develop deploy_production: stage: deploy script: - kubectl set image deployment/myapp myapp=$IMAGE_NAME -n production environment: name: production url: https://example.com when: manual only: - main
Job是CI/CD流程的基本执行单元,包含脚本和规则。
Stage定义Job的执行顺序,同一Stage的Job并行执行。
Pipeline由多个Stage组成,代表完整的CI/CD流程。
定义部署环境(dev、staging、production),支持环境回滚。
build: cache: paths: - node_modules/ artifacts: paths: - dist/ expire_in: 1 week
test_unit: stage: test script: npm run test:unit test_integration: stage: test script: npm run test:integration needs: - test_unit
test: stage: test script: npm run test parallel: matrix: NODE_VERSION: [14, 16, 18] image: node:$NODE_VERSION
deploy: script: deploy.sh rules: - if: '$CI_COMMIT_BRANCH == "main"' when: manual - if: '$CI_PIPELINE_SOURCE == "merge_request_event"' when: on_success
GitLab内置安全扫描工具:
include: - template: Security/SAST.gitlab-ci.yml - template: Security/Secret-Detection.gitlab-ci.yml - template: Security/Container-Scanning.gitlab-ci.yml sast: stage: test container_scanning: stage: test
interruptible: true允许中断only:changes限制特定文件变更触发GitLab CI/CD提供了强大而灵活的自动化能力,是现代DevOps实践的基石。