Gitlab-Runner自動構建伺服器搭建2
註冊Runner
上一節我們建立了自己的gitlab-runner映象,並使用docker-compose up -d --build命令執行了一個名為gitlab-runner-compose的容器;
1、執行register命令註冊runner;
docker exec -it gitlab-runner-compose gitlab-runner-andy register
2、輸入你自己專案倉庫所在gitlab例項的URL:
Please enter the gitlab-ci coordinator URL (e.g. https://gitlab.com )
https://gitlab.com
3、輸入用於註冊Runner的token,從gitlab網站中獲得:
Enter the token you obtained to register the Runner:
*********
4、輸入Runner的描述資訊,之後也可以在gitlab的網站中修改它:
Please enter the gitlab-ci description for this runner
[hostname] nodejs-runner
5、輸入【與Runner關聯的標籤】, 之後也可以在gitlab的網站中修改:
Please enter the gitlab-ci tags for this runner (comma separated):
webapi-tag,another-tag
6、選擇 runner 執行器,這裡選擇的是 shell
Please enter the executor: ssh, docker+machine, docker-ssh+machine, kubernetes, docker, parallels, virtualbox, docker-ssh, shell:
shell
備註:
上述2、3中的URL、TOKEN獲取——專案/Settings/CI_CD/Runners
編寫.gitlab-ci.yml
在專案的根目錄編寫.gitlab-ci.yml檔案:
stages:
- pre_build
- build
- deploy
before_script:
- echo "before_script started."
- docker login --username=${docker_username} --password=${docker_pwd} registry.cn-hangzhou.aliyuncs.com
- echo "end before_script."
# This folder is cached between builds
# http://docs.gitlab.com/ce/ci/yaml/README.html#cache
cache:
paths:
- node_modules/
- dist/
pre_build:
stage: pre_build
script:
- echo "start pre_build."
- npm install
- CI=false npm run build
- echo "end pre_build."
only:
- master
tags:
- webapi-tag
build:
stage: build
script:
- echo "start build."
- docker build -t registry.cn-hangzhou.aliyuncs.com/***/<image>:$CI_COMMIT_SHORT_SHA .
- docker push registry.cn-hangzhou.aliyuncs.com/***/<image>:$CI_COMMIT_SHORT_SHA
- echo "end build."
only:
- master
tags:
- webapi-tag
deploy_job:
stage: deploy
script:
- echo "start deploy."
- docker pull registry.cn-hangzhou.aliyuncs.com/***/<image>:$CI_COMMIT_SHORT_SHA
- docker stop <container> && docker rm <container>
- docker run -id -e NODE_ENV=$NODE_ENV -e MONGODB_URI=$MONGODB_URI -e LAVKEY=$LAVKEY -e LAVSECRET=$LAVSECRET -e LAVHOST=$LAVHOST -e LAVCOUNTRY=$LAVCOUNTRY -e DISH=$DISH -e DISP=$DISP -e DISPWD=$DISPWD -p 3000:3000 --mount source=***-vol,target=/usr/src/app/logs --restart=unless-stopped --name=<container> registry.cn-hangzhou.aliyuncs.com/***/<image>:$CI_COMMIT_SHORT_SHA
- echo "end deploy."
only:
- master
tags:
- webapi-tag
上面的yml檔案把一次 Pipeline 分成了三個階段:
安裝依賴、編譯(pre_build):npm install、npm run build 構建docker映象(build):docker build ……、docker push …… 部署到伺服器(deploy_job):docker pull …… 、docker run ……
stages:定義構建階段,這裡定義了三個階段,分別對應每個階段的stage屬性; script:需要執行的 shell 指令碼; only:only 引數中只有master,意思是隻有master分支有提交的時候才會觸發相關的 Jobs; tags:與註冊 Runner 時輸入的 tag進行匹配。
測試整合效果:
所有操作完成後push程式碼到倉庫的master分支,檢視結果:
passed表示所有stage執行成功。
failed表示失敗,進入Josbs可以檢視log進行排錯: