【问题标题】:Dockerizing react for production not workingDockerizing对生产的反应不起作用
【发布时间】:2022-07-26 01:23:38
【问题描述】:

我创建了一个 DockerfileDocker-compose.yml 用于将我的 create-react-app 容器化到生产环境。我的理解问题是,如果运行命令所需的脚本是dev-dependencies,我应该如何创建生产版本? 我在deployment docs 上也找不到任何东西。

 > [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",   <--- THIS WILL BE USED FOR PRODUCTION
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "devDependencies": {
    "react-scripts": "5.0.1",   <--- THIS WILL NOT BE INSTALLED WITH --production FLAG
    "tailwindcss": "^3.0.24",
    "typescript": "^4.6.3"
  }
}

Dockerfile

FROM node:18-alpine AS builder
ENV NODE_ENV production

# Add a work directory
WORKDIR /app

# Cache and Install dependencies
COPY package.json .
COPY yarn.lock .
RUN yarn install --production   <---- THIS DOES NOT INSTALL DEV DEPENENCIES

# Copy app files
COPY . .

# Build the app
RUN yarn build     <---- THIS CAUSES THE CRASHING

# ---------------------------------------------------

# Bundle static assets with nginx
FROM nginx:1.23.1-alpine AS production
ENV NODE_ENV production

# Copy built assets from builder
COPY --from=builder /app/build /usr/share/nginx/html

# Add your nginx.conf
COPY nginx.conf /etc/nginx/conf.d/default.conf

# Expose port
EXPOSE 80

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

docker-compose.yml

version: "3.8"

services:
  app:
    container_name: my_app
    build:
      context: .
      target: production
      dockerfile: Dockerfile

【问题讨论】:

    标签: reactjs docker nginx docker-compose


    【解决方案1】:

    在最后的映像阶段,您只是COPY --from=builder /app/build 目录,而不是node_modules 树中的任何一个。如果您有开发或生产依赖项,在初始阶段并不重要,因为它们不会出现在最终映像中。

    由于此时您确实需要devDependencies,我将删除yarn install --production 选项。如果它对您的构建环境有影响,您可以在安装依赖项之后设置NODE_ENV=production

    RUN yarn install # not --production
    COPY . .
    # ENV NODE_ENV=production
    RUN yarn build
    

    【讨论】:

      猜你喜欢
      • 2018-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-02
      • 2020-03-14
      • 2019-09-13
      • 2011-01-31
      • 1970-01-01
      相关资源
      最近更新 更多