Docker compose v3 named volume & node_modules from

2019-05-01 16:12发布

问题:

Using compose v3.

In the build I copy package.json and run npm install into

/var/www/project/node_modules

I dont add any code in the build phase.

In compose I add volumes

- ./www:/var/www/project/www

As everyone knows the host bind to /www will effectively "overwrite" the node_modules I installed during the build phase.

Which is why we add a named module afterwards

- ./www:/var/www/project/www
- modules:/var/www/project/www/node_modules

this works fine and dandy the first time we build/run the project

since the named volume "modules" doesnt exist, the www/node_modules from the build phase will be mounted instead.

HOWEVER, in this is the actual issue.

The next time I make a change to package.json and do:

docker-compose up --build 

I can see how the new npm modules are installed but once the named "modules" volume is attached (it now exists stuff there from the previous run) it "overwrites" the newly installed modules in the image.

the above method of adding a named volume is suggested in tons of places as a remedy for the node modules issue. But as far as I can see from lots of testing this only works once.

if I were to rename the named volume every time I make a change to package.json it would of course work.

回答1:

A better thing would be to include rm command in your entrypoint script to clean out node modules before running npm install.

As an alternative, you can use $ docker system prune before running another build. This will make sure that no earlier things are being used.