You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Docker镜像中使用Yarn 2 (Berry)打包VueJS应用?

Yarn 2 Docker 打包适配方案

以下是两种可直接落地的配置方案,可根据你是否启用Zero-Install特性选择:


方案1:适配Zero-Install模式

前置要求

本地已完成Zero-Install配置,且已将.yarn/cache、.yarn/releases、.yarn/plugins、.yarnrc.yml提交到代码仓库,.dockerignore中不要排除上述目录/文件。

调整后的Dockerfile完整配置:

FROM node:14-alpine AS build-stage
# Node 14需手动启用Corepack,Node 16及以上版本默认自带无需该步骤
RUN corepack enable && corepack prepare yarn@stable --activate

WORKDIR /app

# 先复制Yarn相关配置文件,充分利用Docker层缓存能力
COPY .yarn ./.yarn
COPY .yarnrc.yml package.json yarn.lock ./

# Zero-Install模式下该命令仅做依赖校验,几乎无额外耗时
RUN yarn install --immutable

COPY . ./

RUN yarn build --modern \
    && find dist -type f -exec gzip -k "{}" \;

# 生产阶段配置无需改动,和原有逻辑保持一致即可
FROM nginx:mainline-alpine as production-stage

RUN apk add --no-cache curl

HEALTHCHECK CMD curl -f http://localhost || exit 1

COPY docker/entrypoint.sh /
RUN chmod +x /entrypoint.sh

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

ENTRYPOINT [ "/entrypoint.sh" ]

方案2:非Zero-Install常规模式

如果不希望将依赖缓存提交到代码仓库,可使用该方案:

前置要求

在.yarnrc.yml中按需配置nodeLinker(如果项目不兼容PnP模式可设置为node-modules),.dockerignore直接排除整个.yarn目录即可。

调整后的Dockerfile完整配置:

FROM node:14-alpine AS build-stage
RUN corepack enable && corepack prepare yarn@stable --activate

WORKDIR /app

COPY package.json yarn.lock .yarnrc.yml ./

RUN yarn install --immutable --inline-builds

COPY . ./

RUN yarn build --modern \
    && find dist -type f -exec gzip -k "{}" \;

# 生产阶段配置和原有逻辑完全一致
FROM nginx:mainline-alpine as production-stage

RUN apk add --no-cache curl

HEALTHCHECK CMD curl -f http://localhost || exit 1

COPY docker/entrypoint.sh /
RUN chmod +x /entrypoint.sh

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

ENTRYPOINT [ "/entrypoint.sh" ]

额外注意事项

  • --immutable参数强制要求锁文件无变动,避免构建过程生成非预期的依赖版本,非常适合CI/CD场景
  • --inline-builds参数可将依赖构建过程的输出合并到单条日志,降低CI环境的日志冗余
  • 如果项目使用PnP模式,需确保整体工具链完整兼容PnP,否则建议在.yarnrc.yml中设置nodeLinker: node-modules回退到传统node_modules模式

内容的提问来源于stack exchange,提问作者Robert Strauch

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 12:09:03