有了建置 Image 的流程,和前後端分離的機制,接著我們就可以設定 CICD 的流水線來進行服務自動建置和佈署。話不多說了直接演示如下,
專案的資料夾結構
code
frontend
backend
流水線設計內容:
variables:
API_HOME: "code/backend"
FRONT_HOME: "code/frontend"
PROJECT_NAME: "Test"
DOCKER_REGISTRY: "hub.docker.com"
DOCKER_WEB_SERVER_BE: "be"
DOCKER_WEB_SERVER_FE: "fe"
.only_fe_rd_template: &only_fe_rd # 前端的一個共用模板
only:
refs:
- deploy # 觸發的 branch
changes:
- "code/frontend/**/*" # 觸發的目錄
except: # 不會觸發 CICD 的檔案設定
changes:
- "code/frontend/**/*.md"
- "code/frontend/.vscode"
.only_be_rd_template: &only_be_rd # 後端的一個共用模板
only:
refs:
- deploy
changes:
- "code/backend/**/*"
.docker_build_template: &docker_build_rd
image: docker:latest
services:
- docker:dind
variables:
DOCKER_DRIVER: overlay2
.docker_deploy_template: &docker_deploy_rd
image: kroniak/ssh-client
services:
- docker:dind
before_script:
- mkdir -p ~/.ssh
- chmod 700 ~/.ssh
- echo -e "Host *\n\tStrictHostKeyChecking no\n\n" > ~/.ssh/config
- echo "$DEV_SSH_PRIVATE_KEY" > ~/.ssh/id_rsa
- chmod 600 ~/.ssh/id_rsa
stages:
- rd:docker-build-fe
- rd:docker-build-be
- rd:deploy-fe
- rd:deploy-be
before_script:
- export GRADLE_USER_HOME=`pwd`/$API_HOME/.gradle
# Docker build
front-end-docker-build-rd:
stage: rd:docker-build-fe
<<: *docker_build_rd # 注入模板
script:
- echo "build fe"
<<: *only_fe_rd
tags:
- m4-large # gitlab runner 名稱
back-end-docker-build-rd:
stage: rd:docker-build-be
<<: *docker_build_rd
script:
- echo "build be"
<<: *only_be_rd
tags:
- m4-large
## Deploy
ap1-deploy-fe-rd:
stage: rd:deploy-fe
dependencies: # 觸發此流水線前要先完成什麼
- front-end-docker-build-rd
<<: *docker_deploy_rd
script:
- touch fe.md
tags:
- m4-large
<<: *only_fe_rd
ap1-deploy-be-rd:
stage: rd:deploy-be
<<: *docker_deploy_rd
dependencies:
- back-end-docker-build-rd
script:
- ssh $DEV_AWS_USER@$DEV_SERVER_IP "docker login -u $REPOSITORY_ACCOUNT -p $REPOSITORY_PASSWORD DOCKER_REGISTRY"
- ssh $DEV_AWS_USER@$DEV_SERVER_IP "touch be.md"
<<: *only_be_rd
tags:
- m4-large
when: manual # 手動觸發
~$ mkdir -p gitlab-runner/config
~$ docker run -d --name aiot-runner --restart always -v $(pwd)/gitlab-runner/config:/etc/gitlab-runner -v /var/run/docker.sock:/var/run/docker.sock gitlab/gitlab-runner:latest
~$ docker run --rm -it -v $(pwd)/gitlab-runner/config:/etc/gitlab-runner gitlab/gitlab-runner register
Docker 主版 20 以上碰到 DinD 的問題,解決方式如下鏈結1986 issues
在 EC2 建立一個 SSH Key,
ssh-keygen -m PEM -t rsa -b 4096 -C "Some info..."
將 .pub
檔附加至 .ssh/authorized_keys
檔案中
再 gitlab 上 setting -> CI/CD -> Variables
設置 SSH private key
和 IP
以進行連線存取。
下面是觸發資料夾下的內容,如果有達到流水線 changes
的規則會有以下結果,