Develop

CI/CD 自动化部署:GitHub Actions 完整工作流设计与实战

✎ -- 字 🕐 -- 分钟
字号
GitHub Actions CI/CD 流水线

什么是 CI/CD?

持续集成(CI)和持续部署(CD)是现代软件开发的核心实践。GitHub Actions 提供免费的计算资源,让你在代码推送时自动执行编译、测试和部署。

1. 基础工作流结构

# .github/workflows/ci.yml
name: CI Pipeline

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

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

2. 多环境部署

deploy-dev:
  needs: test
  if: github.ref == 'refs/heads/develop'
  runs-on: ubuntu-latest
  steps:
    - uses: actions/checkout@v4
    - name: Deploy to Dev
      run: |
        ssh ${{ secrets.DEV_HOST }} 'cd /app && docker compose pull && docker compose up -d'

deploy-prod:
  needs: test
  if: github.ref == 'refs/heads/main'
  runs-on: ubuntu-latest
  environment: production
  steps:
    - uses: actions/checkout@v4
    - name: Deploy to Production
      run: |
        ssh ${{ secrets.PROD_HOST }} 'cd /app && ./deploy.sh'

3. Docker 镜像构建与推送

build-and-push:
  needs: test
  runs-on: ubuntu-latest
  steps:
    - uses: actions/checkout@v4
    - uses: docker/login-action@v3
      with:
        registry: ghcr.io
        username: ${{ github.actor }}
        password: ${{ secrets.GITHUB_TOKEN }}
    - uses: docker/build-push-action@v5
      with:
        push: true
        tags: ghcr.io/${{ github.repository }}:${{ github.sha }},ghcr.io/${{ github.repository }}:latest

4. 缓存优化

- uses: actions/cache@v3
  with:
    path: |
      ~/.npm
      node_modules
    key: ${{ runner.os }}-node-${{ hashFiles('package-lock.json') }}
    restore-keys: ${{ runner.os }}-node-

5. 矩阵构建

test:
  strategy:
    matrix:
      node-version: [18, 20, 22]
      os: [ubuntu-latest, windows-latest]
  runs-on: ${{ matrix.os }}
  steps:
    - uses: actions/setup-node@v4
      with:
        node-version: ${{ matrix.node-version }}

总结

GitHub Actions 让 CI/CD 变得简单而强大。通过合理设计工作流、利用缓存和矩阵构建,可以实现高效的全链路自动化部署。