手把手教你玩转Git分支策略与GitHub Actions自动化部署

为什么需要Git分支策略?

在实际项目中,如果没有规范的分支管理,开发过程就会变成一场灾难:代码冲突频繁、无法追溯历史、正式环境经常出问题。今天分享一套实用的Git分支策略配合GitHub Actions的CI/CD流程。

推荐的Git分支模型

采用GitFlow的简化版本:

  • main:生产分支,只接受release/hotfix合并
  • develop:开发主分支,功能合并到这里
  • feature/*:功能分支,从develop切出
  • release/*:预发布分支,发布前测试
  • hotfix/*:热修复分支,紧急修复用

基本操作流程

# 开始新功能
git checkout develop
git pull origin develop
git checkout -b feature/my-feature
# 开发完成后合并...
git checkout develop
git merge --no-ff feature/my-feature
git push origin develop
git branch -d feature/my-feature

GitHub Actions自动化部署

在每次push后自动运行测试,通过后部署到服务器。

步骤1:创建Workflow

在仓库创建 .github/workflows/deploy.yml:

name: CI/CD Pipeline

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

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      
      - name: Set up Python
        uses: actions/setup-python@v5
        with:
          python-version: '3.11'
      
      - name: Install dependencies
        run: pip install -r requirements.txt
      
      - name: Run tests
        run: pytest --cov=app tests/

  deploy:
    needs: test
    if: github.ref == 'refs/heads/main'
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      
      - name: Deploy to server
        uses: appleboy/ssh-action@master
        with:
          host: ${{ secrets.HOST }}
          username: ${{ secrets.USERNAME }}
          key: ${{ secrets.SSH_KEY }}
          script: |
            cd /var/www/myapp
            git pull origin main
            docker-compose up -d --build

步骤2:配置Secrets

在GitHub仓库 settings → Secrets → Actions 添加:

  • HOST:服务器IP
  • USERNAME:SSH用户名
  • SSH_KEY:私钥(服务器需添加对应公钥)

步骤3:配置SSH部署密钥

# 服务器上生成密钥
ssh-keygen -t ed25519 -C "github-deploy" -f ~/.ssh/github_deploy
cat ~/.ssh/github_deploy.pub >> ~/.ssh/authorized_keys

Docker Compose完整配置

version: '3.8'

services:
  web:
    build: .
    ports:
      - "8000:8000"
    environment:
      - DATABASE_URL=postgres://user:pass@db:5432/myapp
      - REDIS_URL=redis://cache:6379
    depends_on:
      - db
      - cache
  
  db:
    image: postgres:15-alpine
    volumes:
      - postgres_data:/var/lib/postgresql/data
    environment:
      POSTGRES_USER: user
      POSTGRES_PASSWORD: pass
      POSTGRES_DB: myapp
  
  cache:
    image: redis:7-alpine

volumes:
  postgres_data:

CI/CD完整流程

  1. 开发者push到feature分支 → 自动跑测试
  2. 合并到develop分支 → 再次测试
  3. 合并到main分支 → 测试通过后自动部署
  4. 通过钉钉收到部署通知

常见问题

1. Action超时?

增加timeout-minutes或优化测试用例

2. 部署失败回滚?

手动执行 docker-compose down && git checkout [之前tag]

3. 只部署更改部分?

用paths过滤器,特定文件变更才触发

总结

好的Git分支策略配合GitHub Actions,让团队开发效率大幅提升。关键是:规范化分支管理、自动化测试、安全密钥管理、可回滚部署。从小项目开始逐步完善CI/CD吧!

© 版权声明
THE END
喜欢就支持一下吧
点赞9 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片快捷回复

    暂无评论内容