用Gitea搭建免费Git服务器自定义Actions配置CI/CD自动化部署和测试流水线


发布者 ourjs  发布时间 1767754837774
关键字 devops 

简单来说,Actions CI/CD的核心目标是自动化代码从提交到部署的全流程,减少人工操作、提升交付效率、保障代码质量,

  1. 自动化验证代码质量
    这是 CI/CD 最核心的初衷,通过配置自动化脚本,在代码提交 / 合并前完成校验,避免有问题的代码进入主分支: 代码检查:自动运行 lint(如 ESLint、Pylint)、代码格式校验(如 Prettier、black),确保代码风格统一; 单元测试 / 集成测试:自动执行测试用例(如 JUnit、pytest),统计测试覆盖率,未通过测试则阻止合并; 编译 / 构建验证:对需要编译的项目(如 Go、Java、C++),自动编译检查是否有语法错误,避免「本地能跑、线上编译失败」。 E2E 端到端测试: 模拟真实用户操作,比如:打开网页 → 输入账号密码 → 点击登录 → 提交表单 → 查看结果。从头到尾验证整个系统流程是否能正常跑通的测试方法。
  2. 自动化构建与打包
    代码验证通过后,自动完成构建和制品打包,减少人工打包的繁琐和错误: 构建产物:前端项目自动打包成 dist 静态文件、后端项目编译成可执行文件 / JAR 包; 制作镜像:自动构建 Docker 镜像并推送到镜像仓库(如 Gitea Registry、Harbor); 版本管理:自动生成版本号(如基于提交记录、Tag),打标签并归档制品,方便追溯。
  3. 自动化部署(CD)
    将验证、构建好的产物自动部署到目标环境,实现「代码合并即上线」: 多环境部署:配置不同流水线,自动部署到测试环境(Test)、预发布环境(Staging)、生产环境(Production); 部署方式灵活:支持容器化部署(K8s 发布)、传统部署(SSH 上传文件)、云服务部署(如云函数、容器服务); 回滚机制:配置失败自动回滚,或一键回滚到上一个稳定版本,降低部署风险。

下面将以hotel项目为例,为其搭建CI/CD流水线:FastAPI+SQLModel+PostgreSQL+React+Vite全栈项目文件结构说明环境搭建与初始化指南

本地搭建Gitea

数据库准备

PostgreSQL 中创建 gitea 数据库

准备好服务器/用户名/密码

安装

下载安装Gitea,并启动服务

访问 http://192.168.1.109:3000

初始化Gitea,配置服务器

创建管理员

gitea
user@qq.com
12345678

创建一个用户

daydayup
daydayup@qq.com
12345678

接下来将演示: daydayup 提交合并请求,gitea进行审核

登录并创建仓库

创建一个仓库 hotel

http://192.168.1.109:3000/gitea/hotel

管理员登录,为 hotel 添加用户 daydayup

http://192.168.1.109:3000/gitea/hotel/settings/collaboration

将本地项目推送到 Gitea

推送本地GIT项目 hotel 到 gitea

git remote add origin http://192.168.1.109:3000/gitea/hotel.git
git push -u origin main

Branch Protection Rules 分支保护规则

要让 Gitea 强制只能通过 Pull Request(PR)合并到 main 分支,核心是通过「分支保护规则」禁用直接推送并强制 PR 代码审查,以下是可直接操作的完整步骤与验证方案。

Settings(设置) → 左侧 Branches(分支) → Branch Protection Rules(分支保护规则) → Add Rule(添加规则)

填写规则基础信息

Branch name pattern(分支名称模式):输入 main(或 master,根据你的默认分支名)。
Enable branch protection(启用分支保护):勾选(必须)。
Require pull request reviews before merging: 强制必须通过 PR 合并,禁止直接 push 到 main
Required approvals: 至少 N 人审查通过才可合并(按团队规模调整)
Restrict who can push to matching branches: 彻底禁止任何人直接 push 到 main(含管理员)
Restrict who can create matching branches: 勾选并设置为「Only administrators(仅管理员)」
Block force pushes: 禁止强制推送(git push --force),保护提交历史
Block branch deletion: 禁止删除 main 分支

Create/Review pull request 审批PR

一般的代码合并审查流程,假设A要合并代码到main,此时需要另一个人B进行代码审查。

A: 基于 main 创建分支,提交代码到新分支,并创建PR合并到main
B: 打开 A 的 PR,点开Files Changed,如果有疑问,提交审查意见。点击 Review,点击 Submit review comments,要求A必须解决这个疑问
A: 解决 A 的 Comments,做出相应的修改,并解决这个建议。
B: Approve A 的 PR
A: Merge到main分支(用squash或rebase将多次commit合并成一个)

Gitea Actions CICD配置

在提交代码时,可通过Actions CI/CD运行自动化打包测试、保障代码质量。

仓库启动Actions

管理员权限下,选择需要开启Actions的库,设置-仓库-勾选启用Actions。最新版默认启用

配置Runner

Gitea Actions 需要runner来运⾏作业,可通过docker或二进制文件方式安装runner,这里选择docker进行安装。

获取令牌

获取令牌可通过命令行或页面方式,这里选择通过页面获得令牌。在启用仓库Actions后,设置-Actions-Runner右上角可复制令牌。

Runner容器

使用最新的精简构建版本

docker pull gitea/act_runner:nightly

编写 runner.yaml 配置文件: C:\github\hotel\devops\runner\runner.yaml

修改其中的 gitea 服务器地址和注册令牌 gitea_instance_url gitea_runner_registration_token

# Example configuration file, it's safe to copy this as the default config file without any modification.
# You don't have to copy this file to your instance,
# just run `./act_runner generate-config > config.yaml` to generate a config file.

log:
  # The level of logging, can be trace, debug, info, warn, error, fatal
  level: info

runner:
  # Where to store the registration result.
  file: .runner
  # Execute how many tasks concurrently at the same time.
  capacity: 1
  # Extra environment variables to run jobs.
  envs:
    RUNNER_TOOL_CACHE: /customer/toolcache
    A_TEST_ENV_NAME_1: a_test_env_value_1
    A_TEST_ENV_NAME_2: a_test_env_value_2
  # Extra environment variables to run jobs from a file.
  # It will be ignored if it's empty or the file doesn't exist.
  env_file: .env
  # The timeout for a job to be finished.
  # Please note that the Gitea instance also has a timeout (3h by default) for the job.
  # So the job could be stopped by the Gitea instance if it's timeout is shorter than this.
  timeout: 3h
  # The timeout for the runner to wait for running jobs to finish when shutting down.
  # Any running jobs that haven't finished after this timeout will be cancelled.
  shutdown_timeout: 0s
  # Whether skip verifying the TLS certificate of the Gitea instance.
  insecure: false
  # The timeout for fetching the job from the Gitea instance.
  fetch_timeout: 5s
  # The interval for fetching the job from the Gitea instance.
  fetch_interval: 2s
  # The labels of a runner are used to determine which jobs the runner can run, and how to run them.
  # Like: "macos-arm64:host" or "ubuntu-latest:docker://gitea/runner-images:ubuntu-latest"
  # Find more images provided by Gitea at https://gitea.com/gitea/runner-images .
  # If it's empty when registering, it will ask for inputting labels.
  # If it's empty when execute `daemon`, will use labels in `.runner` file.
  labels:
    # - "windows-latest"
    # - "node-20" 
    - "ubuntu-latest:docker://gitea/runner-images:ubuntu-latest"
    - "ubuntu-22.04:docker://gitea/runner-images:ubuntu-22.04"
    - "ubuntu-20.04:docker://gitea/runner-images:ubuntu-20.04"
  #envs:

cache:
  # Enable cache server to use actions/cache.
  enabled: true
  # The directory to store the cache data.
  # If it's empty, the cache data will be stored in $HOME/.cache/actcache.
  dir: ""
  # The host of the cache server.
  # It's not for the address to listen, but the address to connect from job containers.
  # So 0.0.0.0 is a bad choice, leave it empty to detect automatically.
  host: "192.168.1.109"
  # The port of the cache server.
  # 0 means to use a random available port.
  port: 8090
  # The external cache server URL. Valid only when enable is true.
  # If it's specified, act_runner will use this URL as the ACTIONS_CACHE_URL rather than start a server by itself.
  # The URL should generally end with "/".
  external_server: ""
# Gitea 实例地址
gitea_instance_url: "http://192.168.1.109:3000"
# Runner 的注册 Token
gitea_runner_registration_token: "gWbEc5n49aqtkVRIahSzbhoxDh3RqfpQfnBfZYe0"

# Runner 的名称
gitea_runner_name: "customer_runner"
container:
  # Specifies the network to which the container will connect.
  # Could be host, bridge or the name of a custom network.
  # If it's empty, act_runner will create a network automatically.
  network: ""
  # Whether to use privileged mode or not when launching task containers (privileged mode is required for Docker-in-Docker).
  privileged: false
  # Other options to be used when the container is started (eg, --add-host=my.gitea.url:host-gateway).
  #image: "node:16"  # 默认容器镜像
    # options:
    #  - "run: npm install && npm test"  # 默认运行的命令
  options:
  # The parent directory of a job's working directory.
  # NOTE: There is no need to add the first '/' of the path as act_runner will add it automatically. 
  # If the path starts with '/', the '/' will be trimmed.
  # For example, if the parent directory is /path/to/my/dir, workdir_parent should be path/to/my/dir
  # If it's empty, /workspace will be used.
  workdir_parent:
  # Volumes (including bind mounts) can be mounted to containers. Glob syntax is supported, see https://github.com/gobwas/glob
  # You can specify multiple volumes. If the sequence is empty, no volumes can be mounted.
  # For example, if you only allow containers to mount the `data` volume and all the json files in `/src`, you should change the config to:
  # valid_volumes:
  #   - data
  #   - /src/*.json
  # If you want to allow any volume, please use the following configuration:
  # valid_volumes:
  #   - '**'
  valid_volumes: []
  # overrides the docker client host with the specified one.
  # If it's empty, act_runner will find an available docker host automatically.
  # If it's "-", act_runner will find an available docker host automatically, but the docker host won't be mounted to the job containers and service containers.
  # If it's not empty or "-", the specified docker host will be used. An error will be returned if it doesn't work.
  docker_host: ""
  # Pull docker image(s) even if already present
  force_pull: false
  # Rebuild docker image(s) even if already present
  force_rebuild: false

host:
  # The parent directory of a job's working directory.
  # If it's empty, $HOME/.cache/act/ will be used.
  workdir_parent:

启动 runner

创建 runner_data_customer 目录,运行 docker runner

需要修改 GITEA_INSTANCE_URL GITEA_RUNNER_REGISTRATION_TOKEN 两个参数

docker run -d --name customer_runner --env CONFIG_FILE=/customer/runner.yaml --env GITEA_INSTANCE_URL=http://192.168.1.109:3000 --env GITEA_RUNNER_REGISTRATION_TOKEN=gWbEc5n49aqtkVRIahSzbhoxDh3RqfpQfnBfZYe0 --env GITEA_RUNNER_NAME=customer --env GITEA_RUNNER_LABELS=ubuntu-latest --volume C:\github\hotel\devops\runner\runner.yaml:/customer/runner.yaml --volume C:\github\hotel\devops\runner\runner_data_customer:/customer/runner_data_customer --volume /var/run/docker.sock:/var/run/docker.sock gitea/act_runner:nightly

成功运行后,可以在仓库 -> 设置 -> Actions -> Runner下看到该Runner的信息

配置 Actions

进入对应仓库的设置页面(路径示例:your_gitea.com/<所有者>/仓库名/settings),勾选启用仓库 Actions 选项即可。

创建一个 demo actions,这个DEMO的作用主要是将提交的代码拉取下来

name: Gitea Actions Demo
run-name: ${{ gitea.actor }} is testing out Gitea Actions ߚʯn: [push]

jobs:
  Explore-Gitea-Actions:
    runs-on: ubuntu-latest
    steps:
      - run: echo "ߎ頔he job was automatically triggered by a ${{ gitea.event_name }} event."
      - run: echo "ߐ研his job is now running on a ${{ runner.os }} server hosted by Gitea!"
      - run: echo "ߔhe name of your branch is ${{ gitea.ref }} and your repository is ${{ gitea.repository }}."
      - name: Check out repository code
        run: |
          rm -rf ./hotel && mkdir hotel
          git clone http://192.168.1.109:3000/gitea/hotel.git hotel
          cd hotel
          git checkout ${{ gitea.sha }}
      - run: echo "ߒ᠔he ${{ gitea.repository }} repository has been cloned to the runner."
      - run: echo "ߖ寸he workflow is now ready to test your code on the runner."
      - name: List files in the repository
        run: |
          ls ${{ gitea.workspace }}
      - run: echo "ߍhis job's status is ${{ job.status }}."

push代码后,可在仓库的Actions下看到执行结果。

完整运行流程(按顺序)

  1. 触发条件:代码推送到仓库(on: [push]) 当你向这个 Gitea 仓库执行 git push 操作(任何分支)时,Gitea 会自动检测到 push 事件,触发名为「Gitea Actions Demo」的流水线。
  2. 初始化任务:创建并启动 Runner 容器 Gitea 会根据 runs-on: ubuntu-latest 匹配对应的 Runner(你之前配置的 customer_runner),启动一个 Ubuntu 环境的容器,为后续步骤准备运行环境。 同时,流水线的「运行名称」会显示为「触发者用户名 is testing out Gitea Actions ߚࣀ�褻{ gitea.actor }} 是推送代码的用户名)。
  3. 逐行执行 steps 中的步骤(核心环节)

可配置所有的提交都要检查CI/CD流水线状态,如果运行失败则禁止合并代码.

配置状态检查规则

点击仓库顶部的「Settings」(设置)→ 左侧菜单选择「Branches」(分支)→ 找到「Branch Protection Rules」(分支保护规则)→ 点击「Add Rule」或 「Edit Rule」(修改规则)。

Require status checks to pass before merging: 勾选(强制要求状态检查通过才能合并);
Require branches to be up to date before merging」: 勾选(要求 PR 分支与目标分支同步,避免冲突);
Status checks that are required: 输入你的 CI/CD 流水线「状态名称」(关键!必须和 Actions 流水线的状态名一致),然后点击「Add」添加。即你 demo.yaml 中的 jobs 名称);








  开源的 OurJS
OurJS开源博客已经迁移到 OnceOA 平台。

  关注我们
扫一扫即可关注我们:
OnceJS

OnceOA