CI/CD 完全指南:持续集成与持续部署实战

3 阅读1分钟

apiVersion: apps/v1 kind: Deployment metadata: name: myapp-v1 spec: replicas: 10 selector: matchLabels: version: v1 template: spec: containers: - name: myapp image: myapp:v1

apiVersion: apps/v1 kind: Deployment metadata: name: myapp-canary spec: replicas: 2 selector: matchLabels: version: canary template: spec: containers: - name: myapp image: myapp:v2


### 4.3 滚动更新

```yaml
# Kubernetes Rolling Update
apiVersion: apps/v1
kind: Deployment
metadata:
  name: myapp
spec:
  replicas: 10
  strategy:
    type: RollingUpdate
    rollingUpdate:
      maxSurge: 1
      maxUnavailable: 0

五、测试自动化

5.1 单元测试

test:
  script:
    - npm test
  coverage: /Coverage: \d+\.\d+%/
  artifacts:
    reports:
      junit: junit.xml
      coverage/cobertura: coverage.xml

5.2 E2E 测试

e2e:
  script:
    - npm run build
    - npm run start &
    - sleep 5
    - npx cypress run

六、监控与回滚

6.1 健康检查

health-check:
  script:
    - curl -f http://localhost:3000/health || exit 1

6.2 自动回滚

rollback:
  script: |
    if ! curl -f http://localhost:3000/health; then
      kubectl rollout undo deployment/myapp
      exit 1
    fi

七、实战案例

7.1 完整流程

name: Full CI/CD

on:
  push:
    branches: [main, develop]
  pull_request:

jobs:
  lint:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: '18'
      - run: npm ci
      - run: npm run lint

  test:
    needs: lint
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: '18'
      - run: npm ci
      - run: npm test

  build:
    needs: test
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - run: npm ci
      - run: npm run build
      - uses: actions/upload-artifact@v4
        with:
          name: build
          path: dist

  deploy:
    needs: build
    if: github.ref == 'refs/heads/main'
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/download-artifact@v4
        with:
          name: build
          path: dist
      - name: Deploy
        run: ./deploy.sh

八、总结

CI/CD 核心要点:

  1. CI:持续集成
  2. CD:持续交付/部署
  3. Pipeline:自动化流水线
  4. 测试:单元/E2E
  5. 部署:蓝绿/金丝雀
  6. 回滚:自动回滚

掌握这些,DevOps so easy!