示例文件:
打包前端镜像,推送到 harbor 仓库,然后 连到服务器上更新
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| stages: - build - docker-build
build: stage: build artifacts: paths: - dist script: - source ~/.bashrc - yarn - yarn run build
docker-build: stage: docker-build script: - source ~/.bashrc - docker build -t "registry.harbor.com:55443/test/frontend:${CI_BUILD_REF_NAME}-${CI_JOB_ID}" . - docker push "registry.harbor.com:55443/test/frontend:${CI_BUILD_REF_NAME}-${CI_JOB_ID}" - ssh [email protected] "/opt/kube/bin/kubectl set image deployment/frontend frontend=registry.harbor.com:55443/test/frontend:${CI_BUILD_REF_NAME}-${CI_JOB_ID}"
|
Dockerfile
1 2 3 4 5 6 7 8
| FROM nginx:alpine
COPY ./nginx/nginx.conf /etc/nginx/nginx.conf COPY ./nginx/frontend.conf /etc/nginx/conf.d/default.conf COPY dist/ /opt/frontend/
EXPOSE 80 CMD ["nginx", "-g", "daemon off;"]
|
优化
.gitlab-ci.yml
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| stages: - docker-build
docker-build: stage: docker-build script: - source ~/.bashrc - C_CI_BUILD_REF_NAME=$(echo "${CI_BUILD_REF_NAME}" | tr -d 'v.') - echo "$(cat nginx/test.conf | sed "s/\${CI_BUILD_REF_NAME}/$C_CI_BUILD_REF_NAME/g")" > nginx/test.conf - echo "$(cat Dockerfile | sed "s/\${CI_BUILD_REF_NAME}/$C_CI_BUILD_REF_NAME/g")" > Dockerfile - docker pull nginx:alpine - docker build --build-arg CI_BUILD_REF_NAME=${CI_BUILD_REF_NAME} -t "registry.example.com/test/test-frontend:${CI_BUILD_REF_NAME}" . --network host - docker push "registry.example.com/test/test-frontend:${CI_BUILD_REF_NAME}" - ssh [email protected] "kubectl scale deployment test-frontend-270 --replicas=0 && kubectl scale deployment test-frontend-270 --replicas=3"
|
Dockerfile
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| # 第一阶段:构建前端应用 FROM node:latest as builder
# 设置默认值,可以在构建时通过 --build-arg 参数传递不同的值,利用缓存 ARG CI_BUILD_REF_NAME=${CI_BUILD_REF_NAME}
WORKDIR /app
ENV https_proxy=http://172.20.10.248:1080 ENV http_proxy=http://172.20.10.248:1080
# 升级yarn版本 RUN yarn set version 4.0.2 RUN yarn config set npmRegistryServer https://registry.npmmirror.com
# 将本地的 package.json 和 yarn.lock 复制到容器中 COPY package*.json yarn.lock ./
# 安装项目依赖 RUN node .yarn/releases/yarn-4.0.2.cjs install
# 将应用程序文件复制到工作目录 COPY . .
# 构建前端应用 RUN node .yarn/releases/yarn-4.0.2.cjs run build
FROM nginx:alpine
COPY ./nginx/nginx.conf /etc/nginx/nginx.conf COPY ./nginx/test.conf /etc/nginx/conf.d/default.conf
# 复制第一阶段构建的前端应用到nginx的默认网站目录 COPY --from=builder /app/dist /opt/frontend/test/
EXPOSE 80 CMD ["nginx", "-g", "daemon off;"]
|