记一次KubeSphere前端DevOps构建的艰难历程

446 阅读3分钟

目标

对一个使用了Vue3技术栈的前端项目,在KubeSphere中创建流水线,完成从代码到部署的自动化

问题1:没有合适的agent

使用KubeSphere构建流水线,依赖agent,agent是构建的环境,我们项目的构建依赖于node18、pnpm,这类环境在KubeSphere中都是不存在的。

解决办法1:按照KubeSphere文档,自行构建一个拥有node18、pnpm环境的agent

结论:失败。不管是基于builder-base、还是基于builder-nodejs,都无法正确构建出所需环境。主要原因还是在于最最基础的linux版本老旧,node18依赖的核心类库版本不正确。而如果使用新版的linux,则又无法构建出符合agent要求的基础镜像

解决办法2:构建环境使用node:18,agent使用自带的nodejs,我们把构建(pnpm install、pnpm build)过程放在我们的Dockerfile中

FROM registry.cn-hangzhou.aliyuncs.com/sherry/node:20-alpine-with-pnpm as build-stage

WORKDIR /app

#淘宝
RUN npm config set registry https://registry.npmmirror.com

COPY . .
RUN rm -rf dist node_modules
RUN pnpm install
RUN pnpm build

FROM registry.cn-hangzhou.aliyuncs.com/sherry/nginx:stable-alpine as production-stage

COPY --from=build-stage /app/dist /usr/share/nginx/html


EXPOSE 80

CMD ["nginx", "-g", "daemon off;"]

问题2:登录刷新异常

由于我们是一个单页应用,并且使用了history路由模式。

浏览器显示的地址,实际上并不存在对应的前端资源,所以,部署到nginx后,需要做一些调整

server {
    listen       80; #监听本地80端口,由于nginx运行在容器内,这个本地指的是容器
    server_name  localhost;
    root   /usr/share/nginx/html; #为该目录做静态资源服务
    index  index.html index.htm;
    location / {
        try_files  $uri $uri/ /index.html; #在单页面应用中将不存在的资源重定向到root目录下的index.html
        expires -1; #资源默认不缓存,避免浏览器缓存
    }
    location /static {
        expires 1y; #打包产物static文件夹下的文件的名称带有hash值,可设置一年的长期缓存
    }
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}

把这个nginx配置打包进Docker镜像

FROM dev-image.nbport.com.cn/xintongbuildbase/node:20-alpine-with-pnpm as build-stage

WORKDIR /app

#淘宝
RUN npm config set registry https://registry.npmmirror.com
#官方
#RUN npm config set registry https://registry.npmjs.org/

COPY . .
RUN rm -rf dist node_modules
RUN pnpm install
RUN pnpm build

FROM dev-image.nbport.com.cn/xintongbuildbase/nginx:stable-alpine as production-stage

COPY --from=build-stage /app/dist /usr/share/nginx/html
COPY --from=build-stage /app/nginx.conf /etc/nginx/conf.d/default.conf

EXPOSE 80

CMD ["nginx", "-g", "daemon off;"]

问题3:二阶段构建异常

截止目前,使用该Dockerfile,已经可以在本地打出包了,但是一阶段构建出来的这个dist,在二阶段部署到dist的时候,会有异常。

最终发现是第三方包引用路径大小写敏感导致的,修改第三方组件,重新引入即可

问题4:build访问仓库异常

至此,解决完所有的打包问题,准备去部署流水线了,可是在build环节,发现无法访问仓库

FROM dev-image.nbport.com.cn/xintongbuildbase/node:20-alpine-with-pnpm as build-stage

WORKDIR /app


RUN cat https://registry.npmmirror.com >> a.txt
FROM dev-image.nbport.com.cn/xintongbuildbase/nginx:stable-alpine as production-stage

COPY --from=build-stage /app/a.txt /usr/share/nginx/html


EXPOSE 80

CMD ["nginx", "-g", "daemon off;"]

build这个Dockerfile,就会报找不到registry.npmmirror.com 域名解析的问题

但是宿主机是正常的,最终发现是Docker环境没有正确使用宿主机的网络,所以进行了手动指定

docker build --network host -t XXX .

--network host 是重点