CI/CD流水线设计实践
CI/CD(持续集成/持续部署)是现代软件开发的基石,本文分享流水线设计的最佳实践。
CI/CD 核心概念
- 持续集成(CI):代码提交后自动构建和测试
- 持续交付(CD):自动将代码部署到预发布环境
- 持续部署(CD):自动部署到生产环境
流水线设计
代码
代码提交 → Lint检查 → 单元测试 → 构建 → 集成测试 → 安全扫描 → 部署预发布 → E2E测试 → 部署生产GitHub Actions 配置
yaml
# .github/workflows/ci.yml
name: CI/CD Pipeline
on:
push:
branches: [main, develop]
pull_request:
branches: [main]
env:
NODE_VERSION: '18'
REGISTRY: ghcr.io
jobs:
# 代码检查
lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: ${{ env.NODE_VERSION }}
cache: 'npm'
- run: npm ci
- run: npm run lint
- run: npm run type-check
# 单元测试
test:
runs-on: ubuntu-latest
needs: lint
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: ${{ env.NODE_VERSION }}
- run: npm ci
- run: npm run test:coverage
- name: 上传覆盖率
uses: codecov/codecov-action@v3
# 构建 Docker 镜像
build:
runs-on: ubuntu-latest
needs: test
steps:
- uses: actions/checkout@v4
- uses: docker/setup-buildx-action@v3
- name: 登录镜像仓库
uses: docker/login-action@v3
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: 构建并推送
uses: docker/build-push-action@v5
with:
context: .
push: true
tags: |
${{ env.REGISTRY }}/${{ github.repository }}:latest
${{ env.REGISTRY }}/${{ github.repository }}:${{ github.sha }}
cache-from: type=gha
cache-to: type=gha,mode=max部署策略
滚动部署
yaml
deploy:
runs-on: ubuntu-latest
needs: build
if: github.ref == 'refs/heads/main'
steps:
- name: 滚动更新
run: |
kubectl set image deployment/app
app=${{ env.REGISTRY }}/${{ github.repository }}:${{ github.sha }}
--record
kubectl rollout status deployment/app --timeout=300s蓝绿部署
bash
#!/bin/bash
# 蓝绿部署脚本
NEW_COLOR=$1
OLD_COLOR=$([ "$NEW_COLOR" = "blue" ] && echo "green" || echo "blue")
# 部署新版本
kubectl apply -f k8s/deployment-$NEW_COLOR.yaml
# 等待新版本就绪
kubectl rollout status deployment/app-$NEW_COLOR
# 切换流量到新版本
kubectl patch service app -p '{"spec":{"selector":{"version":"'$NEW_COLOR'"}}}'
# 确认无误后删除旧版本
kubectl delete deployment app-$OLD_COLOR数据库迁移
yaml
migrate:
runs-on: ubuntu-latest
needs: build
steps:
- uses: actions/checkout@v4
- name: 运行数据库迁移
run: |
npx prisma migrate deploy
npx prisma generate
env:
DATABASE_URL: ${{ secrets.DATABASE_URL }}通知集成
yaml
notify:
runs-on: ubuntu-latest
needs: [lint, test, build, deploy]
if: always()
steps:
- name: Slack 通知
uses: slackapi/slack-github-action@v1
with:
payload: |
{
"text": "部署状态: ${{ job.status }}
仓库: ${{ github.repository }}
提交: ${{ github.event.head_commit.message }}"
}
env:
SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK }}最佳实践
- 快速失败:lint 和测试放在前面,快速反馈
- 缓存依赖:加速构建过程
- 并行执行:独立任务并行运行
- 安全扫描:集成 SAST/DAST 工具
- 环境隔离:使用 secrets 管理敏感信息
- 可回滚:每次部署都保留回滚能力
- 监控告警:部署后自动验证服务健康
总结
好的 CI/CD 流水线应该做到:提交即测试、测试通过即构建、构建成功即可部署。GitHub Actions 配置灵活,结合 Docker 和 Kubernetes 可以实现从代码到生产的全自动化。关键是保证流水线的速度和可靠性,让团队专注于写代码而非部署。



评论 2