debian

Debian下GitLab如何集成CI/CD

小樊
57
2025-10-04 16:45:20
栏目: 智能运维

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获取),选择执行器(推荐shelldockerdocker适合隔离环境),设置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的成功

配置说明:

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. 高级优化(可选)

0
看了该问题的人还看了