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

Docker构建报错:yarn build命令未找到,请求技术支持

问题描述

我编写了如下Dockerfile:

FROM node:lts-alpine

WORKDIR /app

COPY package.json ./
COPY yarn.lock ./

COPY client/package.json client/
COPY client/yarn.lock client/
RUN yarn install

COPY server/package.json server/
COPY server/yarn.lock server/
RUN yarn install

COPY client/ client/
RUN yarn build <--- 此处报错
COPY server/ server/

USER node
CMD ["yarn", "start"]
EXPOSE 8000

我的项目包含3个package.json文件,分别位于app根目录、client目录和server目录中,build命令定义在client/package.json中(如下所示):

{
  "name": "myApp",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.14.1",
    "@testing-library/react": "^13.0.0",
    "@testing-library/user-event": "^13.2.1",
    "axios": "^1.3.6",
    "ethers": "5.4.7",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-scripts": "5.0.1",
    "web-vitals": "^2.1.0"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "BUILD_PATH=../server/public react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

执行docker build -t myApp .时,持续收到报错:error Command "build" not found。参考过类似教程,根目录未添加build脚本也能正常运行,刚接触Docker,需要帮助完成项目编译。


解决方法

报错原因很明确:当前工作目录是/app,直接运行yarn build会读取根目录package.json中的脚本,但你的build命令定义在client/package.json里,因此找不到对应命令。

有两种可行的解决方式:

  1. 切换到client目录执行build命令
    修改Dockerfile中的报错行,切换到client目录后再执行build:

    RUN cd client && yarn build
    

    如果你的根目录package.json配置了workspaces(这可能是教程能正常运行的原因),也可以直接通过workspace指定执行client的build脚本:

    RUN yarn workspace client build
    

    若使用workspace方式,需要在根目录package.json中添加如下配置:

    {
      "workspaces": ["client", "server"]
    }
    
  2. 多阶段构建优化镜像(推荐)
    为了缩小最终镜像体积、提升构建效率,可以采用多阶段构建:先完成client的编译,再将产物复制到server环境中,只保留运行必需的依赖:

    # 第一阶段:构建client静态文件
    FROM node:lts-alpine as builder
    WORKDIR /app
    COPY client/package.json client/yarn.lock ./client/
    RUN cd client && yarn install --frozen-lockfile
    COPY client/ ./client/
    RUN cd client && yarn build
    
    # 第二阶段:部署server
    FROM node:lts-alpine
    WORKDIR /app
    COPY server/package.json server/yarn.lock ./server/
    RUN cd server && yarn install --frozen-lockfile --production
    # 从构建阶段复制编译好的静态文件到server的public目录
    COPY --from=builder /app/server/public ./server/public
    COPY server/ ./server/
    
    USER node
    CMD ["yarn", "--cwd", "server", "start"]
    EXPOSE 8000
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 19:45:18