Learn Docker With My Newest Course

Dive into Docker takes you from "What is Docker?" to confidently applying Docker to your own projects. It's packed with best practices and examples. Start Learning Docker →

Docker Tip #75: How to Avoid node_modules in Your Volume Mounts

blog/cards/docker-tips-and-tricks.jpg

Volume mounts are great in development, but it's usually not great when you end up with node_modules on your Docker host.

I don’t know about you but, I’m not a fan of having 5 trillion Javascript files end up on my Docker host because the node_modules directory happens to have gotten volume mounted. This would typically happen if you were volume mounting .:/app in development.

If you’re using yarn, you can prevent that from happening very easily without having to resort to using hacks.

1. Create a .yarnrc file in the same location as your package.json:

Then add this line to the file: --modules-folder /node_modules.

By doing that, your node modules will get installed to /node_modules instead of relative to your package.json file which means they won’t be volume mounted back to your dev box if you do a volume mount such as .:/app.

2. Adjust your Dockerfile:

You’re likely copying in your package.json file before you copy in all of your code to leverage Docker’s ability to cache layers.

Adjust that COPY line to be: COPY package.json *yarn* ./

Now your .yarnrc (and yarn.lock) will be copied along with your package.json.

3. Update any script paths:

With your node modules living in /node_modules, you may need to update certain script paths if you reference them, such as using webpack.

Now you would reference /node_modules/webpack/bin/webpack.js --mode=production -p or whatever script you’re planning to run.

This same strategy applies to other language package managers that install dependencies to relative folders by default (such as Mix with Elixir or Composer with PHP).

Free Intro to Docker Email Course

Over 5 days you'll get 1 email per day that includes video and text from the premium Dive Into Docker course. By the end of the 5 days you'll have hands on experience using Docker to serve a website.


Comments