10

I have a React Node.js project running on docker. I was able to make it work by following the article here.

The problem is that node_modules folder on my host machine is empty. Changing the volumes to /www/project/node_modules:app/node_modules will render the modules unavailable in the docker container.

The workaround that I'm using is to install only the dependencies on my host machine by running npm install --only=dev. However, they disappear every time I restart the container.

Here is a copy of my Github repo that does this.

1 Answer 1

9

So there are few things here, you need to deviate from that article. Because that articles uses anonymous volume for the node_modules. In your case you want the devDepencies to come to your host also, so you can use them.

Now Node will not allow two different folders for dependencies until your use requirejs module and configure multiple sources in that. So for your development image what you want is that yarn is not run inside the Dockerfile. Instead it is run when the container starts

So I will change the Dockerfile as

FROM node:7.10.1

ENV HOME=/home/app
COPY package.json $HOME/react/
COPY scripts $HOME/react/scripts/
RUN npm install yarn -g
WORKDIR $HOME/react
ENV NODE_PATH=/home/node_modules
VOLUME $NODE_PATH
CMD yarn start:dev

Then update docker-compose.yml

react:
  build: .
  ports:
   - 3100:3100
  volumes:
    - .:/home/app/react
    - ./node_modules:/home/node_modules

Now if you do docker-compose up the node_modules is empty. So what you should do whenever you want to refresh the packages

docker-compose run react yarn
docker-compose up -d

Using NODE_PATH we changed the location of node_modules to /home/node_modules inside the container. Then in docker-compose we mapped the same to ./node_modules on host. So our first docker-compose run react yarn, will fill this folder with all the dependencies.

From next time you just run docker-compose up. Any time you want to update dependencies you either run "yarn" inside the react container or you just run the docker-compose run ... command again

2
  • This is brilliant!
    – Mr A
    Commented Aug 26, 2017 at 14:08
  • The key line here really is: what you want is that yarn is not run inside the Dockerfile. Instead it is run when the container starts. Unfortunately, this does mean that you cannot take advantage of Docker caching that step and it will rerun each time you start your container.
    – Akaisteph7
    Commented Sep 21, 2023 at 19:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.