CI/CD 是持续集成(Continuous Integration)和持续部署(Continuous Deployment)的缩写,是现代软件开发的核心实践。本指南将指导您搭建一个完整的私有 CI/CD 环境,包含代码托管、自动化测试和部署能力。
一、GitLab 部署详解
1. 安装依赖
- 最低服务器配置:4 核 8G(建议生产环境更高配置)
- 操作系统:CentOS 7 + 或类似 Linux 发行版
- 网络:需开放 80/443 端口(GitLab Web 访问)
2. 安装依赖
yum upgrade
yum install -y curl policycoreutils-python-utils openssh-server perl
3. 添加 GitLab 仓库
curl -sS https://packages.gitlab.com/install/repositories/gitlab/gitlab-ce/script.rpm.sh | sudo bash
4. 安装 GitLab
sudo EXTERNAL_URL="http://gitlab.example.com" yum install -y gitlab-ce
将 http://gitlab.example.com 替换为你实际的域名或 IP 地址。
5. 配置并启动 GitLab
sudo gitlab-ctl reconfigure
二、部署 GitLab Runner
1. 添加 GitLab Runner 仓库
curl -L https://packages.gitlab.com/install/repositories/runner/gitlab-runner/script.rpm.sh | sudo bash
2. 安装 GitLab Runner
sudo yum install gitlab-runner -y
3. 注册 Runner
登录 GitLab (gitlab.example.com)替换为实际域名。
可通过 cat /etc/gitlab/initial_root_password 查看管理员密码。
- 使用管理员账号登录 GitLab
- 点击 "New Project" -> 创建空白项目
- 记录项目 URL(如:git@gitlab.example.com:root/new_project.git)
安装Runner
curl -L "https://packages.gitlab.com/install/repositories/runner/gitlab-runner/script.rpm.sh" | sudo bash
yum install gitlab - runner
创建一个Runners并配置
- 登录 GitLab -> 项目 -> Settings -> CI/CD -> Runners
- 找到 "Register a group runner" 或 "Register a project runner"
gitlab-runner register --url http://gitlab.example.com --token glrt-xx_xxxx_xxxxxxxxxxx
克隆远程仓库到本地
git clone ssh://git@gitlab.example.com:root/new_project.git
cd new_project
创建 .gitlab-ci.yml 文件
stages:
- lint
- test
- build
- deploy
# 代码检查阶段
lint:
stage: lint
image: alibaba-cloud-linux-3-registry.cn-hangzhou.cr.aliyuncs.com/alinux3/python
script:
- pip install flake8
- export PATH="$PATH:$(python -m site --user-base)/bin" # 添加用户级别的可执行文件路径
- flake8 .
only:
- main
- merge_requests
# 测试阶段
test:
stage: test
image: alibaba-cloud-linux-3-registry.cn-hangzhou.cr.aliyuncs.com/alinux3/python
script:
- pip install pytest
- /home/gitlab-runner/.local/bin/pytest # 使用绝对路径调用 pytest
only:
- main
# 构建阶段(这里假设只是打印构建信息,可按需修改)
build:
stage: build
image: alibaba-cloud-linux-3-registry.cn-hangzhou.cr.aliyuncs.com/alinux3/python
script:
- echo "Building Python project..."
only:
- main
# 部署阶段
deploy:
stage: deploy
image: alibaba-cloud-linux-3-registry.cn-hangzhou.cr.aliyuncs.com/alinux3/python
script:
- echo "deploy Success!"
创建测试文件 test_example.py
def test_demo():
assert 1 + 1 == 2
配置git全局信息并提交触发CI
git config --global user.email "you@example.com"
git config --global user.name "Your Name"
git add 。
git commit -m "add .gitlab-ci.yml"
git push origin main
三、执行结果验证
-
登录 GitLab -> 项目 -> CI/CD -> Pipelines
-
查看各阶段执行状态(绿色表示成功,红色表示失败)
-
失败处理:
- 查看作业日志定位问题
- 检查配置文件语法(可使用CI Lint 工具) 至此已完成最基本的CI/CD流程。