Why does docker create empty node_modules and how to avoid it?

You are right, your image building process is installing the node packages into the node_modules directory in the image. So, after you build your image the image contains node_modules and you can use it to run your application.

You see node_modules on your host machine, because of your volumes setup in your Compose file. There is more to it than you see in the other answer though.

What's happening is that you are mapping .:/usr/app in your first volume definition, which means that you are mapping your current directory on the host to /usr/app in the container.

This will override the /usr/app directory in the image with the current directory on the host. And your host does not have the node_modules directory (unless you installed node_modules on the host, too) and therefore your container will not work with this mapping, beacuse you've overriden /usr/app and there is no node_modules dir in the override. Node will throw an error that it cannot find node modules.

The next volume mapping solves the situation, this is actually a common Node development setup. You create a volume /usr/app/node_modules. Note, that this volume does not have a host part there is no : in the mapping, there is only one directory here. This means that Docker will mount the /usr/app/node_modules directory from the image and add it to the previous mapping where you mapped the host dir to /usr/app.

So in the running container you'll have your source code from the host's current directory PLUS node_modules from the underlying image due to the double mapping.

As a side effect you'll see an empty node_modules directory in your host's current directory.

Tags:

Docker

Node.Js