1. 在Debian上安装GitLab
首先更新系统并安装必要依赖,确保系统软件包为最新状态:
sudo apt update && sudo apt upgrade -y
sudo apt install curl openssh-server ca-certificates postfix -y
添加GitLab官方仓库(替换$(lsb_release -cs)为Debian发行版代号,如bookworm):
curl -sS https://packages.gitlab.com/install/repositories/gitlab/gitlab-ce/script.deb.sh | sudo bash
安装GitLab Community Edition(CE):
sudo apt install gitlab-ce -y
配置GitLab实例,编辑/etc/gitlab/gitlab.rb文件,设置external_url为服务器IP或域名(如http://192.168.1.100):
sudo vim /etc/gitlab/gitlab.rb
保存后重新配置并启动GitLab服务:
sudo gitlab-ctl reconfigure
sudo systemctl start gitlab && sudo systemctl enable gitlab
通过浏览器访问external_url,完成初始管理员账号设置(默认用户名root)。
2. 安装与配置GitLab Runner
GitLab Runner是执行CI/CD作业的代理,需单独安装。在Debian上执行以下命令:
curl -L https://packages.gitlab.com/install/repositories/runner/gitlab-runner/script.deb.sh | sudo bash
sudo apt install gitlab-runner -y
注册Runner到GitLab项目:
sudo gitlab-runner register
按提示输入GitLab实例URL(如http://192.168.1.100)和注册令牌(从GitLab项目Settings → CI/CD → Runners获取),选择执行器(推荐shell或docker,docker适合隔离环境),设置Runner描述(如debian-runner)和标签(如ci)。
启动Runner服务并设置开机自启:
sudo systemctl daemon-reload
sudo systemctl start gitlab-runner && sudo systemctl enable gitlab-runner
验证Runner状态:
sudo gitlab-runner status
确保Runner显示为running。
3. 编写.gitlab-ci.yml配置文件
在项目根目录创建.gitlab-ci.yml文件,定义CI/CD流程(以Java项目为例):
stages:
- build
- test
- deploy
variables:
MAVEN_OPTS: "-Dmaven.repo.local=.m2/repository"
build_job:
stage: build
script:
- echo "Downloading dependencies..."
- mvn dependency:go-offline
- echo "Compiling and packaging..."
- mvn package -DskipTests
artifacts:
paths:
- target/*.jar
expire_in: 1 hour
test_job:
stage: test
script:
- echo "Running unit tests..."
- mvn test
needs: ["build_job"] # 依赖build_job的artifacts
deploy_job:
stage: deploy
script:
- echo "Deploying to production server..."
- scp target/*.jar user@production-server:/opt/app/
- ssh user@production-server "systemctl restart app-service"
only:
- main # 仅main分支触发部署
needs: ["test_job"] # 依赖test_job的成功
配置说明:
stages:定义流程阶段(build→test→deploy),作业按阶段顺序执行。artifacts:build_job生成的target/*.jar文件会传递给后续test_job使用。needs:指定作业依赖关系,确保前序作业成功后再执行。only:限制deploy_job仅在main分支推送时触发。4. 触发CI/CD流水线
将.gitlab-ci.yml文件提交到GitLab仓库并推送:
git add .gitlab-ci.yml
git commit -m "Add CI/CD configuration with build, test, and deploy stages"
git push origin main
推送后,GitLab会自动检测.gitlab-ci.yml文件,触发流水线。可通过GitLab项目页面CI/CD → Pipelines查看流水线状态,点击作业名称查看详细日志(如构建输出、测试结果)。
5. 高级优化(可选)
docker执行器,并在.gitlab-ci.yml中使用Docker镜像(如image: maven:3.8.7-openjdk-17),避免本地环境差异。variables中配置CI_REGISTRY_USER和CI_REGISTRY_PASSWORD(从GitLab项目Settings → CI/CD → Variables获取)。certbot工具),提升数据传输安全性(参考GitLab官方文档)。