一、前置准备:安装并配置GitLab
在Linux服务器上部署GitLab是实现项目托管的基础,需完成以下步骤:
sudo apt update && sudo apt upgrade);安装必要依赖(curl、openssh-server、ca-certificates、tzdata、postfix,其中postfix用于邮件通知)。curl https://packages.gitlab.com/install/repositories/gitlab/gitlab-ce/script.deb.sh | sudo bash,CentOS执行类似rpm命令);安装GitLab CE(社区版):sudo apt install gitlab-ce(Ubuntu)或sudo yum install gitlab-ce(CentOS)。/etc/gitlab/gitlab.rb设置外部访问URL(如EXTERNAL_URL="http://your_server_ip");运行sudo gitlab-ctl reconfigure应用配置;启动服务(sudo gitlab-ctl start)并设置开机自启(sudo systemctl enable gitlab-ce)。二、配置GitLab Runner(CI/CD执行引擎)
GitLab Runner是执行.gitlab-ci.yml中任务的工具,需在Linux服务器(部署目标服务器)上安装并注册:
curl -L --output /etc/apt/trusted.gpg.d/gitlab.asc https://packages.gitlab.com/gitlab/gitlab-runner/gpgkey
echo "deb https://packages.gitlab.com/gitlab/gitlab-runner/ubuntu $(lsb_release -cs) main" | tee /etc/apt/sources.list.d/gitlab-runner.list
sudo apt update && sudo apt install gitlab-runner -y
sudo gitlab-runner register,按提示输入:
http://your_gitlab_server_ip);linux,用于匹配项目中的标签限制)。三、创建.gitlab-ci.yml(CI/CD流程定义)
在项目根目录下创建.gitlab-ci.yml文件,定义构建→测试→部署的自动化流程。以下是一个Java项目的示例:
stages:
- build # 构建阶段:编译代码
- test # 测试阶段:运行单元测试
- deploy # 部署阶段:推送代码到生产服务器
variables:
MAVEN_OPTS: "-Dmaven.repo.local=.m2/repository" # Maven本地仓库路径
build_job:
stage: build
script:
- echo "开始构建项目..."
- mvn clean package -DskipTests # 编译并跳过测试(测试由单独阶段执行)
artifacts: # 将构建产物(如jar包)传递给后续阶段
paths:
- target/*.jar
only:
- master # 仅master分支触发
test_job:
stage: test
script:
- echo "运行单元测试..."
- mvn test # 执行测试用例
only:
- master
deploy_job:
stage: deploy
script:
- echo "开始部署到生产服务器..."
- scp -o StrictHostKeyChecking=no target/*.jar user@your_production_server:/opt/app/ # 使用scp传输文件
- ssh user@your_production_server "cd /opt/app && nohup java -jar *.jar > app.log 2>&1 &" # 后台启动应用
only:
- master
when: manual # 手动触发部署(避免自动部署风险,可选)
关键说明:
stages:定义流程阶段顺序,需按build→test→deploy依次执行;script:每个阶段的执行命令(如mvn package、scp);artifacts:将前一阶段的输出(如jar包)传递给后续阶段;only:指定触发分支(如master),避免其他分支误触发;when: manual:手动触发部署,适合生产环境风险控制。四、配置SSH免密登录(Runner访问目标服务器)
为了让Runner能通过scp/ssh将代码部署到目标Linux服务器,需配置SSH免密登录:
ssh-keygen -t rsa,按提示保存密钥(默认路径~/.ssh/id_rsa),无需设置密码。ssh-copy-id user@your_production_server(user为目标服务器用户名),将公钥添加到目标服务器的~/.ssh/authorized_keys文件中。ssh user@your_production_server,若无需输入密码即可登录,则配置成功。五、触发CI/CD流程
完成上述配置后,每次向GitLab项目的master分支提交代码(或合并Pull Request),GitLab会自动触发CI/CD流水线:
六、进阶优化(可选)
.gitlab-ci.yml中配置缓存,加快构建速度(如缓存Maven的localRepository或Node.js的node_modules):cache:
paths:
- .m2/repository/ # Maven缓存
- node_modules/ # Node.js缓存
image: maven:3.8.6-openjdk-11),避免环境差异问题;或通过Docker构建应用镜像并推送到镜像仓库(如Docker Hub)。kubectl命令实现滚动更新、自动扩缩容等高级部署功能(需配置KUBECONFIG变量指向kubeconfig文件)。.gitlab-ci.yml中添加通知步骤(如邮件、Slack),在流水线失败时及时通知团队:notify_job:
stage: .post # 在所有阶段后执行
script:
- echo "发送失败通知..."
- curl -X POST -H 'Content-type: application/json' --data '{"text":"Pipeline failed!"}' $SLACK_WEBHOOK_URL
when: on_failure
需提前在GitLab CI/CD Variables中配置SLACK_WEBHOOK_URL(敏感信息建议使用变量而非硬编码)。