在Debian上使用GitLab CI的完整步骤
确保Debian系统已更新并安装基础依赖,避免后续安装冲突:
sudo apt update && sudo apt upgrade -y
sudo apt install -y curl openssh-server ca-certificates postfix
安装Postfix时,选择“Internet Site”类型并配置域名/SMTP(可选,但建议用于邮件通知)。
若需在Debian上托管自己的GitLab仓库,需完成以下步骤:
curl -sS https://packages.gitlab.com/install/repositories/gitlab/gitlab-ce/script.deb.sh | sudo bash
sudo apt install gitlab-ce
/etc/gitlab/gitlab.rb,设置external_url(如http://your-server-ip或域名),保存后重新配置并启动服务:sudo gitlab-ctl reconfigure
sudo gitlab-ctl restart
访问http://your-server-ip,使用初始管理员账号(root)登录。GitLab Runner是执行.gitlab-ci.yml中任务的代理,需单独安装:
curl -L https://packages.gitlab.com/install/repositories/runner/gitlab-runner/script.deb.sh | sudo bash
sudo apt install gitlab-runner
http://your-gitlab-url)和注册Token(从GitLab项目→Settings→CI/CD→Runners获取):sudo gitlab-runner register
选择执行器(推荐docker或shell,docker适合隔离环境,shell适合直接在主机执行),设置Runner描述(如debian-runner)和标签(如linux)。在项目根目录创建.gitlab-ci.yml文件,定义流水线的阶段(stages)和任务(jobs)。以下是一个通用示例:
stages:
- build # 构建阶段
- test # 测试阶段
- deploy # 部署阶段
variables:
PROJECT_NAME: "my-app" # 自定义变量,可在任务中引用
build_job:
stage: build
script:
- echo "Installing dependencies..."
- apt-get update && apt-get install -y make gcc # 示例:安装编译工具
- echo "Building project..."
- make # 替换为实际构建命令(如mvn、gradle、npm等)
artifacts:
paths:
- build/ # 保存构建产物,供后续job使用
test_job:
stage: test
script:
- echo "Running unit tests..."
- make test # 替换为实际测试命令(如pytest、junit等)
deploy_job:
stage: deploy
script:
- echo "Deploying to production..."
- scp -r build/* user@your-server:/var/www/${PROJECT_NAME} # 示例:SCP部署到远程服务器
only:
- master # 仅master分支推送时触发
when: manual # 可选:手动触发部署(避免自动部署风险)
注意:根据项目语言调整脚本(如Node.js项目用npm install、npm test;Python项目用pip install -r requirements.txt)。
将.gitlab-ci.yml提交到GitLab仓库,GitLab Runner会自动检测并执行流水线:
git add .gitlab-ci.yml
git commit -m "Add GitLab CI/CD configuration"
git push origin master # 推送至master分支(或其他触发分支)
触发后,可在GitLab项目→CI/CD→Pipelines页面查看流水线状态(通过/失败)、日志及每个job的输出。
若需在CI/CD中访问远程服务器(如部署),需配置SSH密钥:
ssh-keygen -t rsa -b 4096 -C "gitlab-ci@example.com"
~/.ssh/id_rsa.pub内容,在GitLab项目→Settings→CI/CD→Variables中添加变量SSH_PUBLIC_KEY。.gitlab-ci.yml的before_script中添加:before_script:
- 'which ssh-agent || ( apt-get update -y && apt-get install -y openssh-client )'
- eval $(ssh-agent -s)
- echo "$SSH_PRIVATE_KEY" | tr -d '\r' | ssh-add - > /dev/null # 使用项目变量中的私钥
- mkdir -p ~/.ssh
- chmod 700 ~/.ssh
- ssh-keyscan your-server.com >> ~/.ssh/known_hosts # 替换为实际服务器域名/IP
- chmod 644 ~/.ssh/known_hosts
若项目依赖特定环境(如Python、Node.js),可直接在.gitlab-ci.yml中指定Docker镜像,避免手动安装依赖:
image: python:3.9 # 使用Python 3.9镜像
stages:
- test
test_job:
stage: test
script:
- pip install -r requirements.txt # 安装依赖
- pytest # 运行测试
通过cache指令缓存依赖目录,减少重复下载时间:
cache:
paths:
- .cache/pip/ # Python pip缓存
- node_modules/ # Node.js依赖目录
build_job:
stage: build
script:
- pip install -r requirements.txt
- npm install
通过以上步骤,即可在Debian上完成GitLab CI的搭建与使用,实现项目的自动化构建、测试和部署。