概念梳理

自动化部署&DevOps - 图1

配置文件

以下是前端工程部署的.gitlab-ci.yml文件和Dockerfile文件示例。

.gitlab-ci.yml

  1. stages: # 分段
  2. - build
  3. - deploy
  4. cache: # 缓存
  5. paths:
  6. - node_modules
  7. - build
  8. # ----------------------------------------------【测试环境】
  9. npm:
  10. tags:
  11. - guarantee-test
  12. only:
  13. - test
  14. stage: build
  15. image: node:14.15.4
  16. script:
  17. - npm i --save --registry=https://registry.npm.taobao.org
  18. - npm run build
  19. docker:
  20. tags:
  21. - guarantee-test
  22. only:
  23. - test
  24. stage: build
  25. script:
  26. - docker build -t guarantee-pc:latest .
  27. - docker tag guarantee-pc:latest docker-registry.xjchenhao.com/xxx/guarantee-pc:$CI_COMMIT_REF_NAME
  28. - docker login --username=$harborUserName --password=$harborPassword http://docker-registry.rd.com
  29. - docker push docker-registry.xjchenhao.com/xxx/guarantee-pc:$CI_COMMIT_REF_NAME
  30. deploy:
  31. tags:
  32. - guarantee-test
  33. only:
  34. - test
  35. stage: deploy
  36. before_script:
  37. - 'command -v ssh-agent >/dev/null || ( apt-get update -y && apt-get install openssh-client -y )'
  38. - eval $(ssh-agent -s)
  39. - echo "$TEST_PRIVATE_KEY" | tr -d '\r' | ssh-add -
  40. - mkdir -p ~/.ssh
  41. - chmod 700 ~/.ssh
  42. script:
  43. - ssh -o StrictHostKeyChecking=no root@"$TEST_SERVER_IP" ./docker-deploy-web.sh guarantee-pc "$CI_COMMIT_REF_NAME" 8001

Dockerfile

  1. FROM nginx
  2. COPY build /usr/share/nginx/html
  3. RUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime && echo "Asia/Shanghai" > /etc/timezone
  4. EXPOSE 80

Shell

  1. #/bin/bash
  2. set -e;
  3. service_name="$1"
  4. tag="$2"
  5. port="$3"
  6. docker pull docker-registry.xjchenhao.com/xxx/$service_name:$tag;
  7. docker run --rm curlimages/curl:latest 'https://oapi.dingtalk.com/robot/send?access_token=123456789' \
  8. -H 'Content-Type: application/json' \
  9. -d '{"msgtype": "text","text": {"content": "【xxx测试环境服务器】\n⚠️ '$service_name:$tag'开始部署"}}'
  10. docker stop $service_name||true;
  11. docker rm $service_name||true;
  12. docker run -d -p $port:80 --name $service_name docker-registry.rd.com/ztb/$service_name:$tag;
  13. docker run --rm curlimages/curl:latest 'https://oapi.dingtalk.com/robot/send?access_token=8b4fdd45b8e851dcb1191ab081f8eb61f664dbbbbefc78fb17112d0d0d731556' \
  14. -H 'Content-Type: application/json' \
  15. -d '{"msgtype": "text","text": {"content": "【xxx测试环境服务器】\n✅ '$service_name:$tag'部署成功"}}'
  16. docker image prune -a -f;

参考文章

  1. Gitlab-ci:从零开始的前端自动化部署
  2. Docker — 从入门到实践
  3. Gitlab YAML 详解