如何将我的 Docker React 容器配置为仅在需要时安装模块?



我正在尝试在我的docker-compose.yml文件中构建几个Docker服务,这些服务将启动我的Django/MySql后端以及我的React客户端应用程序。 我在我的docker-compose.yml中有这个部分来处理React部分....

client:
build:
context: ./client
volumes:
- ./client:/app
ports:
- '3001:3000'
restart: always
container_name: web-app
environment:
- NODE_ENV=development
- REACT_APP_PROXY=http://localhost:9090
depends_on:
- web

然后我构建了以下客户端/Dockerfile 来配置 React 容器......

FROM node:10-alpine AS alpine
# A directory within the virtualized Docker environment
# Becomes more relevant when using Docker Compose later
WORKDIR /app/
# Copies package.json and package-lock.json to Docker environment
COPY package*.json ./
# Installs all node packages
RUN npm install
# Finally runs the application
CMD [ "npm", "start" ]

但是当我的容器启动时,它会因以下错误而死亡......

web-app   | Failed to compile.
web-app   | 
web-app   | ./node_modules/react-tag-input/dist-modules/components/ReactTags.js
web-app   | Module not found: Can't resolve 'react-dnd' in '/app/node_modules/react-tag-input/dist-modules/components'

我以为我上面的"运行 npm 安装"会挽救这一天,但我想不是。 有没有办法以某种方式检测哪些模块未安装并在我的容器启动时安装它们?

编辑:包.json

{
"name": "client",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^4.2.4",
"@testing-library/react": "^9.4.0",
"@testing-library/user-event": "^7.2.1",
"bootstrap": "^4.4.1",
"jquery": "^1.9.1",
"react": "^16.12.0",
"react-bootstrap": "^1.0.0-beta.17",
"react-device-detect": "^1.12.1",
"react-dom": "^16.12.0",
"react-hamburger-menu": "^1.2.1",
"react-native-flash-message": "^0.1.15",
"react-router-dom": "^5.1.2",
"react-scripts": "3.3.1",
"react-tag-input": "^6.4.3",
"typescript": "^3.8.3"
},
"scripts": {
"start": "react-scripts start",
"build": "NODE_ENV=development react-scripts build",
"build:prod": "NODE_ENV=production react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"proxy": "http://localhost:8000",
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}

这里发生了两件事:

  1. 您的volumes:指令会覆盖/app树中的所有内容,包括node_modules
  2. 您的 Dockerfile 实际上并没有将应用程序代码COPY到映像中(因此您需要使用volumes:将其放在那里的解决方法(。

您可以通过更新您的 Dockerfile 来解决此问题

FROM node:10-alpine
WORKDIR /app/
COPY package*.json ./
RUN npm install
# Actually copy the application code in
COPY . ./
CMD ["npm", "start"]

如果还没有.dockerignore文件,请创建包含行node_modules的文件,以防止该主机目录内置到映像中。

最后,从docker-compose.yml文件中删除volumes:

如果更改前端代码,则需要docker-compose up --build才能重新生成映像。

如果你想要一个实时开发环境,你可以直接在主机上使用 Node,即使你的堆栈的大部分其余部分都在 Docker 中运行。 对于前端代码尤其如此:由于提供的代码实际上在最终用户的浏览器中运行,因此它无法直接与Docker网络通信,或者根本无法真正利用Docker。

# Start everything besides the front-end
docker-compose up -d web
# Start a dev server in the usual way
export NODE_ENV=development
export REACT_APP_PROXY=http://localhost:9090
npm start

最新更新