Skip to content

CI/CD 流水线使用 GitHub 操作

入门 约 25 分钟

你将构建什么

GitHub 操作 workflow 那个运行 on 每个推送, 安装 dependencies, 运行测试, and 构建项目 automatically.

学习目标

  • 理解 GitHub 操作 workflow 语法
  • 创建 workflow 那个触发 on 推送事件
  • 添加构建 and 测试 stages 到流水线
  • View 流水线 results in GitHub UI

前置要求

  • GitHub account and 仓库使用节点.js 项目
  • 基础理解的 YAML 语法
  • 项目使用 `npm 测试` and `npm 运行构建` scripts

步骤

  1. 1

    创建 workflow directory

    GitHub 操作 workflows live in .github/workflows/ directory. 创建这个 directory 结构 in 你的仓库.

    代码
    mkdir -p .github/workflows

    预期结果

    .github/workflows directory exists in 你的项目.

  2. 2

    编写 workflow file

    创建 file named CI.yml in workflows directory. 定义 workflow 那个触发 on 推送 and 拉取请求, 运行 on Ubuntu, 检查 out code, 安装 dependencies, 运行测试, and 构建.

    代码
    name: CI
    on: [push, pull_request]
    jobs:
      build-and-test:
        runs-on: ubuntu-latest
        steps:
          - uses: actions/checkout@v3
          - uses: actions/setup-node@v3
            with:
              node-version: 18
          - run: npm ci
          - run: npm test
          - run: npm run build

    预期结果

    workflow file exists 那个定义 CI 流水线.

  3. 3

    提交 and 推送

    提交 workflow file and 推送到 GitHub. GitHub 将 automatically detect workflow and 开始运行它.

    代码
    git add .github/workflows/ci.yml
    git commit -m "Add CI pipeline"
    git push

    预期结果

    推送触发 workflow. Go 到 '操作' tab in GitHub 到 see 它运行.

  4. 4

    Review results

    Go 到 '操作' tab in 你的 GitHub 仓库. 你应该 see 你的 workflow 运行. 点击 on 它到 view logs for 每个步骤.

    预期结果

    workflow shows green checkmarks for 每个步骤, meaning 构建 and 测试通过.

  5. 5

    添加健康检查端点

    为应用添加 /health 端点返回 200 OK,供编排系统(Kubernetes、负载均衡器)探测存活。健康检查是生产部署的基础设施。

    代码
    # app.py (Flask example)
    from flask import Flask, jsonify
    app = Flask(__name__)
    
    @app.route("/health")
    def health():
        return jsonify({"status": "ok"}), 200
    
    @app.route("/ready")
    def ready():
        # Check DB connection etc.
        return jsonify({"ready": True}), 200

    预期结果

    curl localhost:5000/health 返回 {"status":"ok"} 和 200 状态码。

自己动手试试

你学到了什么

你构建 CI 流水线使用 GitHub 操作那个 automatically 测试 and 构建你的 code on 每个推送. 这个 catches bugs early and ensures 你的 code 是总是 in buildable 状态.

相关资源

相关术语

相关术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误

← 返回主题