NodeJS: Making docker-compose Volumes Ignore the node_modules Directory

NodeJS: Making docker-compose Volumes Ignore the node_modules DirectoryKeeping your node_modules from disappearing when you map your app volumesSemur NabievBlockedUnblockFollowFollowingJun 11The PurposeIn this piece, I’ll show you how to install node_modules on docker-compose build instead of docker-compose up and not have them disappear when you map your app volumes.

Code snippets can be found at the bottom of the article.

The ProblemIf you use Docker, you probably also use Docker Compose.

Which means you map your app volume to the container volume.

Unfortunately, when you do this, your local (and empty) node_modules folder will overwrite the container node_modules folder.

The SolutionA workaroundAs a workaround, you can doCMD npm install && npm run dev.

The problem with that approach is:It slows down the docker-compose up commandIt makes Docker Hyperkit take up a lot more CPU than it needsA better solutionHave docker install node_modules on docker-compose build and run the app on docker-compose up.

Folder structure:docker-compose.

yml:Dockerfile:Note — need to copy package.

json first because volume mapping happens on the docker-compose up command, and so this file does not exist on build yetCommon errorsIf you had already built the containers and installed packages into the node_modules directory, it’s best to clean up before trying this by removing all your containers and images related to the project# will remove everythingdocker container rm -f $(docker container ls -qa)docker image rm -f $(docker image ls -q)2.

If you install a new module, you have to rebuild the image.

To do that, run:# remove the image where the new module is installed.

remember, $CONTAINER_FOLDER is the name of this imagedocker image rm -f $CONTAINER_FOLDER# rebuild, while making sure it doesn't use the internal cache docker-compose build –no-cachedocker-compose up.. More details

Leave a Reply