高级前端
前端工程化
【Q736】前端如何对分支环境进行部署

前端如何对分支环境进行部署

Issue 欢迎在 Gtihub Issue 中回答此问题: Issue 762 (opens in a new tab)

Author 回答者: AndyTiTi (opens in a new tab)

以下是基于gitlab的分支和tag进行前端部署的.gitlab-ci.yml配置

image: node:12-alpine3.14
stages: # 分段
  # - install
  - build
  - deploy
  - clear

cache: # 缓存
  paths:
    - node_modules

job_install:
  tags:
    - test
  stage: build
  script:
    - npm install -g cnpm --registry=https://registry.npm.taobao.org
    - cnpm install
    - npm run build
  # 只在指定dev分支或者tag以 dev_ 开头的标签执行该job
  only:
    refs:
      - dev
      - /^dev_[0-9]+(?:.[0-9]+)+$/ # regular expression
  # 打包后的文件可以在gitlab上直接下载
  artifacts:
    name: "dist"
    paths:
      - dist

job_deploy:
  image: docker
  stage: deploy
  environment:
    name: test
    url: http://172.6.6.6:8000
  script:
    - docker build -t appimages .
    - if [ $(docker ps -aq --filter name=app-container) ]; then docker rm -f app-container;fi
    - docker run -d -p 8082:80 --name app-container appimages

job_clear:
  image: docker
  stage: clear
  tags:
    - test
  script:
    - if [ $(docker ps -aq | grep "Exited" | awk '{print $1 }') ]; then docker stop $(docker ps -a | grep "Exited" | awk '{print $1 }');fi
    - if [ $(docker ps -aq | grep "Exited" | awk '{print $1 }') ]; then docker rm $(docker ps -a | grep "Exited" | awk '{print $1 }');fi
    - if [ $(docker images | grep "none" | awk '{print $3}') ]; then docker rmi $(docker images | grep "none" | awk '{print $3}');fi

Author 回答者: shfshanyue (opens in a new tab)

一种基于容器及 docker-compose 或者 k8s 的思路

  1. 借用现有的 CICD 服务,如 github actions 或者 gitlab CI 获取当前分支信息
  2. 借用 Docker 快速部署前端或者后端,根据分支信息启动不同的服务 (Service)根据 Docker 启动服务并配置响应的标签 (Label)
  3. 根据容器的标签与当前 Git 分支对前端后端设置不同的域名

以下是一个 Preview 的示例,其中服务名 cra-preview-${COMMIT_REF_NAME} 基于分支名称进行构建。

version: "3"
services:
  cra-preview-${COMMIT_REF_NAME}:
    build:
      context: .
      dockerfile: router.Dockerfile
    labels:
      # 配置域名: Preview
      - "traefik.http.routers.cra-preview-${COMMIT_REF_NAME}.rule=Host(`${COMMIT_REF_NAME}.cra.shanyue.tech`)"
      - traefik.http.routers.cra-preview-${COMMIT_REF_NAME}.tls=true
      - traefik.http.routers.cra-preview-${COMMIT_REF_NAME}.tls.certresolver=le

在进行构建时,再通过 envsub 工具进行环境变量的替换

cat preview.docker-compose.yaml | envsubst > docker-compose.yaml