Git多人协作实战:分支策略与GitHub Actions自动化CI/CD部署指南

在团队开发中,Git分支管理混乱和手动部署是两大痛点。本文介绍一套实用的Git协作规范,并结合GitHub Actions实现代码推送后自动测试、构建、部署的完整CI/CD流水线。

一、Git分支策略规范

推荐采用简化版Git Flow,适合中小团队:

  • main:生产分支,只接受来自release或hotfix的合并,禁止直接push
  • develop:开发主干,功能分支从此拉取,合并后触发测试
  • feature/xxx:功能分支,命名如 feature/user-login,完成后提PR合并到develop
  • hotfix/xxx:线上紧急修复,从main拉取,修复后同时合并回main和develop

团队约定:每个PR至少需要1人Code Review通过才能合并,避免单点失误。

二、GitHub Actions CI/CD配置

在项目根目录创建 .github/workflows/deploy.yml,实现推送到main分支时自动部署到服务器:

name: Deploy to Production

on:
  push:
    branches: [ main ]

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v3

      - name: Setup Node.js
        uses: actions/setup-node@v3
        with:
          node-version: "18"

      - name: Install & Build
        run: |
          npm ci
          npm run build

      - name: Deploy via SSH
        uses: appleboy/ssh-action@master
        with:
          host: ${{ secrets.SERVER_HOST }}
          username: ${{ secrets.SERVER_USER }}
          key: ${{ secrets.SSH_PRIVATE_KEY }}
          script: |
            cd /var/www/myapp
            git pull origin main
            npm ci --production
            pm2 restart app

三、配置Secrets安全存储

敏感信息(服务器IP、SSH密钥)不能写死在配置文件里,需存入GitHub Secrets:

  • 进入仓库 → Settings → Secrets and variables → Actions
  • 添加 SERVER_HOSTSERVER_USERSSH_PRIVATE_KEY 三个Secret
  • 工作流中通过 ${{ secrets.XXX }} 引用,安全且不泄露

四、PR保护规则设置

在 Settings → Branches → Branch protection rules 中为main分支开启:

  • Require pull request reviews before merging(至少1人审核)
  • Require status checks to pass(CI通过才能合并)
  • Restrict who can push to matching branches(限制直接push权限)

五、常用Git协作命令速查

# 从develop创建功能分支
git checkout develop && git pull
git checkout -b feature/add-payment

# 提交规范(Conventional Commits)
git commit -m "feat: 新增支付宝支付模块"
git commit -m "fix: 修复订单金额计算错误"
git commit -m "docs: 更新API接口文档"

# 合并前同步develop最新代码(rebase保持线性历史)
git fetch origin
git rebase origin/develop

# 推送并创建PR
git push origin feature/add-payment

遵循统一的分支规范 + 自动化CI/CD,可以大幅减少人为失误,让团队专注于业务开发而非繁琐的手动部署。建议从小项目开始实践,逐步完善流水线。

© 版权声明
THE END
喜欢就支持一下吧
点赞7 分享