结合前一篇文章搭建的gitlab服务 Ubuntu20.04 搭建 gitlab 服务,继续测试CI/CD 部署项目。
准备一台web服务测试机与gitlab服务隔离
gitlab :192.168.5.196
web : 192.168.5.187
1,准备工作、配置项目目录及启动配置
1.1 docker-compose.yml 配置如下
# docker-compose.yml
version: "3.6"
services:
local-halobug:
image: nginx:1.19.4-alpine
restart: always
expose:
- 80
networks:
- traefik
labels:
- "traefik.enable=true"
- "traefik.docker.network=traefik"
- "traefik.http.routers.local_halobug.entrypoints=http"
- "traefik.http.routers.local_halobug.rule=Host(`nginx.halobug.cn`)"
- "traefik.http.services.local_halobug-backend.loadbalancer.server.scheme=http"
- "traefik.http.services.local_halobug-backend.loadbalancer.server.port=80"
logging:
driver: "json-file"
options:
max-size: "1m"
networks:
traefik:
external: true
1.2 update.sh 启动脚本
#!/usr/bin/env bash
# 关闭服务
echo "stop services."
docker-compose down --remove-orphans
# 重启服务
echo 'restart services.'
docker-compose up -d
1.3 .gitlab-ci.yml 配置文件
# 脚本可根据需要自行更改(测试使用)
variables:
PROJECT_WORKDIR: /root/halobug/$CI_PROJECT_NAME
DEPLOY_TARGET_01: ${DEPLOY_TARGET_01}
stages:
- deploy
部署线上01:
stage: deploy
tags:
- shell
script:
- ssh $DEPLOY_TARGET_01 "rm -rf $PROJECT_WORKDIR"
- scp -r $CI_PROJECT_DIR $DEPLOY_TARGET_01:$PROJECT_WORKDIR
- ssh $DEPLOY_TARGET_01 "cd $PROJECT_WORKDIR && bash update.sh"
完整目录结构
别急此时部署还是阻塞状态
继续安装….
2,安装 runner(国内较慢)
// 添加官方GitLab存储库
curl -L "https://packages.gitlab.com/install/repositories/runner/gitlab-runner/script.deb.sh" | sudo bash
//安装最新版本的GitLab Runner
sudo -E apt-get install gitlab-runner
3,注册 runner
// 注册 Runner (根据提示输入相关内容)
sudo gitlab-runner register
(sudo gitlab-runner register 执行后的截图)
查找URL+token的配置方式 注册成功后的截图如下
3.1,配置CI/CD 变量(gitlab-ci有使用变量)
4,切换runner 用户测试是否能ssh web目标机器
4.1 切换用户
su gitlab-runner
4.2 生成ssh key
// 回车键一直按就行了
ssh-keygen -t rsa -C "gitlab@halobug.cn"
4.3 将生成的 ~/.ssh/id_rsa.pub 配置到web 目标机器 ~/.ssh/authorized_keys
4.4 完成4.3配置后ssh 测试
ssh root@192.168.5.187
成功如下图
4.5 重试发布流程,如下图
4.6 绑定hosts访问 nginx.halobug.cn
// 本机测试绑定 hosts
192.168.5.187 nginx.halobug.cn
Welcome to nginx!