Gitlab CI/CD 自动化部署

Gitlab CI/CD 自动化部署


今天尝试完成了一个 Gitlab 前端 Vue 项目的自动化部署流水线,接下来介绍一下我做的工作

1. 初步准备

  • 首先需要安装 gitlab-cegitlab-runner

这一步我不会,我们的后端帮我装好了,我只要负责剩下的部分就好了

  • 将项目推送到 Gitlab 上,然后在项目中新建 .gitlab-ci.yml 文件

2. 安装环境

因为刚开始我没给服务器安装环境所以给我报了个错误:

$ echo "=====start install======"
=====start install======
$ npm install
bash: line 123: npm: command not found
Cleaning up project directory and file based variables
00:00
ERROR: Job failed: exit status 1

所以意识到不对,马上开始安装,输入如下命令:

yum install nodejs
yum install npm

等待安装完成,如果能查看版本成功,那么说明安装没问题:

node -v
npm -v

3. 开始配置 yml 文件

在项目的根目录下新建 .gitlab-ci.yml 文件,文件中写入如下配置:

stages: # Stages 表示构建阶段,这里有两个阶段 install, deploy
  - install
  - deploy

cache:
  key: ${
    
    CI_BUILD_REF_NAME}
  paths:
    - node_modules/
    
install-staging:dep: # Jobs 表示构建工作,表示某个 Stage 里面执行的工作。
  stage: install
  tags:
    - 你自己的 runner 名字 #runner执行器的名字,与注册runner时填写的tags保持一致
  only: # 定义了只有在被merge到了master分支上 才会执行部署脚本。
  	- master
  script:
  	- echo "=====start install======"
  	- npm install  #安装依赖
  	- echo "=====end install======"
  artifacts:  # 将这个job生成的依赖传递给下一个job。需要设置dependencies
    expire_in: 60 mins   # artifacets 的过期时间
    paths:  # 需要被传递给下一个job的目录。
    	- node_modules/
    
deploy-staging:dep:
  stage: deploy
  tags:
    - 你自己的 runner 名字
  only:
  	- master
  script:
    - echo "=====start build======"
    - npm run build  # 将项目打包
    - echo "=====end build======"
    - echo "=====start deploy======"
    - cp -rf ./dist/  你自己放 Vue 项目的绝对路径
    - echo "=====end deploy!!!!!!======"

4. 部署

只要将其他分支 merge 进去 master 分支,那么会自动进行部署啦。

成功后会有如下打印:

$ echo "=====start install======"
=====start install======
$ npm install
......
$ echo "=====end install======"
=====end install======
......
Job succeeded
$ echo "=====end build======"
=====end build======
$ echo "=====start deploy======"
=====start deploy======
$ cp -rf ./dist/  /usr/local/nginx/html/
$ echo "=====end deploy!!!!!!======"
=====end deploy!!!!!!======
......
Job succeeded

如果两个任务都成功完成那么部署就算成功了

5. 遇到的问题

  • $ npm install
    npm ERR! code ENOTFOUND
    npm ERR! errno ENOTFOUND
    npm ERR! network request to https://registry.npmjs.org/vue-loader failed, reason: getaddrinfo ENOTFOUND registry.npmjs.org
    npm ERR! network This is a problem related to network connectivity.
    npm ERR! network In most cases you are behind a proxy or have bad network settings.
    npm ERR! network 
    npm ERR! network If you are behind a proxy, please make sure that the
    npm ERR! network 'proxy' config is set properly.  See: 'npm help config'
    npm ERR! A complete log of this run can be found in:
    npm ERR!     /root/.npm/_logs/2022-11-08T09_57_14_281Z-debug.log
    Cleaning up project directory and file based variables
    00:00
    ERROR: Job failed: exit status 1
    

    只要配置淘宝镜像即可:

    npm config set registry https://registry.npm.taobao.org
    

猜你喜欢

转载自blog.csdn.net/ox4f5da2/article/details/127757861