1257 字
6 分钟
CI/CD:持续集成与持续部署

什么是工作流?#

工作流是一系列相互关联的步骤或任务的自动化序列,用于完成特定的业务目标。在软件开发中,工作流通常包括:

  • 代码检查:自动运行代码质量检查
  • 测试执行:自动运行单元测试、集成测试
  • 构建打包:自动编译和打包应用程序
  • 部署发布:自动将应用程序部署到目标环境

CI/CD:持续集成与持续部署#

持续集成(CI)#

持续集成是一种开发实践,要求开发人员频繁地(通常是每天多次)将代码集成到主分支中。每次集成都通过自动化构建来验证,包括编译、测试等步骤。

CI的核心原则:

  • 频繁提交代码
  • 自动化构建和测试
  • 快速反馈
  • 保持主分支稳定

持续部署(CD)#

持续部署是持续集成的延伸,指的是将通过所有测试的代码自动部署到生产环境。

CD的两种形式:

  1. 持续交付(Continuous Delivery):自动化部署到预生产环境,手动部署到生产环境
  2. 持续部署(Continuous Deployment):全自动化部署到生产环境

主流工作流平台#

1. GitHub Actions#

GitHub Actions是GitHub提供的CI/CD平台,与GitHub仓库深度集成。

基本配置示例:

name: CI/CD Pipeline
on:
push:
branches: [ main, develop ]
pull_request:
branches: [ main ]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Setup Node.js
uses: actions/setup-node@v3
with:
node-version: '18'
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Run tests
run: npm test
- name: Run linting
run: npm run lint
build:
needs: test
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Setup Node.js
uses: actions/setup-node@v3
with:
node-version: '18'
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Build application
run: npm run build
- name: Upload build artifacts
uses: actions/upload-artifact@v3
with:
name: build-files
path: dist/

2. GitLab CI/CD#

GitLab CI/CD使用.gitlab-ci.yml文件定义工作流。

配置示例:

stages:
- test
- build
- deploy
variables:
NODE_VERSION: "18"
before_script:
- apt-get update -qq && apt-get install -y -qq git curl
- curl -sL https://deb.nodesource.com/setup_${NODE_VERSION}.x | bash -
- apt-get install -y nodejs
test:
stage: test
script:
- npm ci
- npm run test
- npm run lint
coverage: '/Lines\s*:\s*(\d+\.\d+)%/'
build:
stage: build
script:
- npm ci
- npm run build
artifacts:
paths:
- dist/
expire_in: 1 hour
deploy:
stage: deploy
script:
- echo "Deploying application..."
- # 部署脚本
only:
- main

3. Jenkins#

Jenkins是最老牌的CI/CD工具,具有丰富的插件生态系统。

Jenkinsfile示例:

pipeline {
agent any
tools {
nodejs "18"
}
stages {
stage('Checkout') {
steps {
git 'https://github.com/your-repo.git'
}
}
stage('Install') {
steps {
sh 'npm ci'
}
}
stage('Test') {
parallel {
stage('Unit Tests') {
steps {
sh 'npm run test:unit'
}
}
stage('Linting') {
steps {
sh 'npm run lint'
}
}
}
}
stage('Build') {
steps {
sh 'npm run build'
archiveArtifacts artifacts: 'dist/**', fingerprint: true
}
}
stage('Deploy') {
when {
branch 'main'
}
steps {
sh 'echo "Deploying to production..."'
// 部署脚本
}
}
}
post {
always {
cleanWs()
}
failure {
mail to: 'team@company.com',
subject: "Build Failed: ${env.JOB_NAME} - ${env.BUILD_NUMBER}",
body: "Build failed. Check console output."
}
}
}

工作流最佳实践#

1. 分支策略#

Git Flow策略:

  • main:生产环境代码
  • develop:开发分支
  • feature/*:功能开发分支
  • release/*:发布准备分支
  • hotfix/*:紧急修复分支

GitHub Flow策略:

  • main:始终可部署的代码
  • feature/*:功能分支,通过PR合并到main

2. 测试策略#

# 多层测试策略
test-pyramid:
unit-tests:
description: "快速、大量的单元测试"
tools: ["Jest", "Mocha", "Vitest"]
integration-tests:
description: "验证组件间协作"
tools: ["Cypress", "Playwright"]
e2e-tests:
description: "端到端功能测试"
tools: ["Selenium", "Puppeteer"]

3. 部署策略#

蓝绿部署:

deploy:
blue-green:
steps:
- name: "Deploy to Green Environment"
script: deploy-green.sh
- name: "Health Check"
script: health-check.sh
- name: "Switch Traffic"
script: switch-traffic.sh
- name: "Cleanup Blue Environment"
script: cleanup-blue.sh

金丝雀部署:

deploy:
canary:
strategy:
canary:
steps:
- setWeight: 10
- pause: {duration: 300s}
- setWeight: 50
- pause: {duration: 300s}
- setWeight: 100

监控和日志#

工作流监控#

monitoring:
metrics:
- build_duration
- test_success_rate
- deployment_frequency
- mean_time_to_recovery
alerts:
- name: "Build Failure"
condition: "build_status == 'failed'"
notification: "slack, email"
- name: "Long Build Time"
condition: "build_duration > 30m"
notification: "slack"

日志管理#

logging:
structured_logs:
format: "json"
fields:
- timestamp
- level
- message
- build_id
- commit_hash
aggregation:
tools: ["ELK Stack", "Fluentd", "Grafana"]

安全考虑#

密钥管理#

secrets:
storage:
- github_secrets
- vault
- k8s_secrets
best_practices:
- never_commit_secrets
- rotate_regularly
- principle_of_least_privilege

安全扫描#

security_scanning:
dependency_check:
tools: ["npm audit", "Snyk", "OWASP Dependency Check"]
code_analysis:
tools: ["SonarQube", "CodeQL", "ESLint Security"]
container_scanning:
tools: ["Trivy", "Clair", "Docker Bench"]

工作流优化技巧#

1. 缓存策略#

# GitHub Actions缓存示例
- name: Cache dependencies
id: cache
uses: actions/cache@v3
with:
path: ~/.npm
key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
restore-keys: |
${{ runner.os }}-node-

2. 并行化#

# 并行执行测试
jobs:
test:
strategy:
matrix:
node-version: [16, 18, 20]
os: [ubuntu-latest, windows-latest, macos-latest]

3. 条件执行#

# 只在特定条件下执行
- name: Deploy
if: github.ref == 'refs/heads/main'
run: npm run deploy

总结#

工作流是现代软件开发的基石,它通过自动化减少了人为错误,提高了开发效率,并确保了代码质量。选择合适的工作流平台和策略,结合最佳实践,可以显著提升团队的开发体验和产品质量。

记住,好的工作流应该是:

  • 简单易懂:团队成员容易理解和维护
  • 快速反馈:能够快速发现和定位问题
  • 可靠稳定:减少误报和中断
  • 安全可控:确保代码和部署的安全性

通过不断优化和改进工作流,我们可以构建更加高效和可靠的软件开发流程。

CI/CD:持续集成与持续部署
https://fuwari.vercel.app/posts/workflows/
作者
Lorem Ipsum
发布于
2025-09-04
许可协议
CC BY-NC-SA 4.0