React.js Docker - Module not found

2019-08-21 02:23发布

问题:

Prerequisites

Linux 18.04

create-react-app 2.0

docker 19.09.0

Dockerfile

# base image
FROM node:9.6.1

# set working directory
RUN mkdir /usr/src/app
WORKDIR /usr/src/app

# add `/usr/src/app/node_modules/.bin` to $PATH
ENV PATH /usr/src/app/node_modules/.bin:$PATH
ADD package.json /package.json

# install and cache app dependencies
COPY package.json /usr/src/app/package.json
RUN npm install --save --silent
RUN npm install react-scripts@latest -g --silent

# start app
CMD ["npm", "start"]

docker-compose.yml

version: '3.5'

services:

  provisioning-app:
    container_name: prv-app
    build:
      context: .
      dockerfile: Dockerfile
    volumes:
      - '.:/usr/src/app'
      - '/usr/src/app/node_modules'
    ports:
      - '3000:3000'
    environment:
      - NODE_ENV=development

Problem

Everything has been working just fine, but after installing a new package docker stopped working as expected. Every time I run docker-compose up it fails with 'Module not found' error. While npm start works perfectly fine. I've tried quite a few workarounds found on the web:

  • restart PC
  • delete node_modules folder and run npm i again
  • different combinations of npm install / --save / including --save in Dockerfile

It just doesn't work and I can't handle it on my own. Any ideas why this might be happening?

Update

Weirdly, but this code works. I'm a rookie in Docker, so I have no clue what's the difference

docker run -it \
  -v ${PWD}:/usr/src/app \
  -v /usr/src/app/node_modules \
  -p 3000:3000 \
  --rm \
  prov-app

回答1:

Everything has been working just fine, but after installing a new package docker stopped working as expected. Every time I run docker-compose up it fails with 'Module not found' error.

You need to rebuild your image to have that package installed. docker-compose build, and then docker-compose up

EDIT

Based on your update, I realize that the problem is your old node_module volume persisted between builds. Try docker-compose down -v before up.



回答2:

Instead of:

volumes:
  - '.:/usr/src/app'
  - '/usr/src/app/node_modules'

Try:

volumes:
  - ./:/usr/src/app
  - /usr/src/app/node_modules