🔑 GitHub Actions 使用流程(从头到尾)

1. 启用 GitHub Actions

  • 打开 GitHub 仓库 → 点击 Actions 标签页。
  • GitHub 会给你推荐一些常见的工作流模板(Node.js、Java、Python 等),也可以选择 自己新建 workflow

2. 创建 workflow 配置文件

  • 在项目根目录下新建:

    .github/workflows/ci.yml
    
  • 这是 Actions 的核心配置文件,使用 YAML 语法描述 CI/CD 流程。


3. 配置 workflow 基本信息

示例:Node.js 项目自动测试

name: CI Pipeline   # 工作流名称

on:                 # 触发条件
  push:             # 推送时触发
    branches: [ main ]
  pull_request:     # PR 时触发
    branches: [ main ]

jobs:               # 一个 workflow 可以包含多个 job
  build:
    runs-on: ubuntu-latest   # 运行环境(虚拟机)

    steps:          # job 中的每一步
      - name: Checkout code
        uses: actions/checkout@v3   # 拉取代码

      - name: Setup Node.js
        uses: actions/setup-node@v3
        with:
          node-version: '18'        # 设置 Node 版本

      - name: Install dependencies
        run: npm install

      - name: Run tests
        run: npm test

4. (可选)添加环境变量 & secrets

  • 如果需要连接数据库、部署到服务器,需要配置 Secrets

    • 打开仓库 → Settings → Secrets and variables → Actions → 新建 DEPLOY_KEYDB_PASSWORD 等。
  • 在 workflow 文件里这样引用:

    - name: Deploy
      run: ssh user@server "deploy.sh"
      env:
        DEPLOY_KEY: ${{ secrets.DEPLOY_KEY }}
    

5. 提交代码,触发 workflow

  • 提交 ci.yml 到仓库:

    git add .github/workflows/ci.yml
    git commit -m "add github actions ci"
    git push origin main
    
  • GitHub 会自动启动 Actions,你可以在 Actions 面板看到执行日志。


6. 查看结果 & 调试

  • 每一步执行都会在日志中展示输出。
  • 如果失败,可以点开对应步骤查看错误信息。
  • 修改 .yml 文件再 push 即可重新运行。

7. 扩展:常见使用场景

  • CI(持续集成):跑单元测试、Lint 检查。
  • CD(持续部署):构建并部署到服务器、云服务(如 AWS、Vercel、Docker Hub)。
  • 自动化:定时任务(on: schedule)、自动发布 npm 包、生成 changelog。

✅ 总结

在 GitHub Actions 里一般的操作步骤是:
首先在项目中新建 .github/workflows/xxx.yml 文件,然后在里面配置触发条件(比如 push 到 main 分支)、运行环境(如 ubuntu-latest)、以及每个执行步骤(checkout 代码、安装依赖、运行测试、构建部署)。
如果需要敏感信息,会在仓库的 Secrets 中配置,然后在 workflow 里引用。最后我会提交代码,GitHub 自动执行,并在 Actions 面板查看执行日志。
实际开发中我常用它做 CI 测试和自动部署。

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐