Docker部署Create React App生产环境失败问题求助
Create React App容器化构建报错:
react-scripts not found 解决方案 问题描述
为Create React App编写Dockerfile和docker-compose.yml做生产环境容器化部署时遇到问题:执行构建命令依赖的react-scripts属于dev-dependencies,但使用--production参数安装依赖时不会包含它,导致无法生成生产构建包,且官方部署文档中未找到相关解决办法。
报错信息
> [builder 7/7] RUN yarn build: #13 0.507 yarn run v1.22.19 #13 0.556 $ react-scripts build #13 0.579 /bin/sh: react-scripts: not found #13 0.590 error Command failed with exit code 127. #13 0.590 info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command. ------ executor failed running [/bin/sh -c yarn build]: exit code: 127 ERROR: Service 'app' failed to build : Build failed `docker-compose` process finished with exit code 1
相关配置文件
package.json
{ "version": "0.1.0", "private": true, "dependencies": { "react": "^18.1.0", "react-dom": "^18.1.0", "react-i18next": "^11.17.2", "react-router-dom": "^6.3.0", }, "scripts": { "start": "react-scripts start", "build": "react-scripts build", // 用于生产环境 "test": "react-scripts test", "eject": "react-scripts eject" }, "devDependencies": { "react-scripts": "5.0.1", // 使用--production flag不会安装 "tailwindcss": "^3.0.24", "typescript": "^4.6.3" } }
Dockerfile
FROM node:18-alpine AS builder ENV NODE_ENV production # 添加工作目录 WORKDIR /app # 缓存并安装依赖 COPY package.json . COPY yarn.lock . RUN yarn install --production # 不会安装开发依赖 # 复制应用文件 COPY . . # 构建应用 RUN yarn build # 此处导致报错 # --------------------------------------------------- # 使用nginx打包静态资源 FROM nginx:1.23.1-alpine AS production ENV NODE_ENV production # 从builder阶段复制构建后的资源 COPY --from=builder /app/build /usr/share/nginx/html # 添加nginx配置 COPY nginx.conf /etc/nginx/conf.d/default.conf # 暴露端口 EXPOSE 80 # 启动nginx CMD ["nginx", "-g", "daemon off;"]
docker-compose.yml
version: "3.8" services: app: container_name: my_app build: context: . target: production dockerfile: Dockerfile
解决方案
问题核心是构建阶段必须安装dev-dependencies,react-scripts是构建过程的必要工具,但最终生产镜像不需要这些依赖,因此要利用Docker多阶段构建的特性,在builder阶段安装全部依赖,构建完成后只把产物复制到生产镜像中。
修改后的Dockerfile
# builder阶段:安装全部依赖并构建 FROM node:18-alpine AS builder WORKDIR /app # 复制依赖配置文件 COPY package.json yarn.lock ./ # 安装所有依赖(包括devDependencies) RUN yarn install # 复制源码并构建生产包 COPY . . RUN yarn build # production阶段:仅复制构建产物到nginx,不携带任何依赖 FROM nginx:1.23.1-alpine AS production ENV NODE_ENV production COPY --from=builder /app/build /usr/share/nginx/html COPY nginx.conf /etc/nginx/conf.d/default.conf EXPOSE 80 CMD ["nginx", "-g", "daemon off;"]
可选优化
- 可以使用
yarn install --frozen-lockfile替代yarn install,确保依赖版本与本地一致,避免构建差异 - 若想进一步缩小builder阶段的临时体积,可在构建完成后执行
rm -rf node_modules,但由于多阶段构建不会将builder的文件带入生产镜像,此步骤非必需
内容的提问来源于stack exchange,提问作者bitsmyth
相关产品推荐
相关产品推荐

