Docker compose. The volume inside another volume on the same container. How does it work?

I’m trying to create a relatively simple setup to develop and test npm packages. A problem was in the fact, that after you mounted a code volume to the container it replaces node_modules.

I tried a lot of generally logical stuff, mostly aimed to move node_modules to another location and then reference it within configuration files. It works, but the solution is ugly. Also, it’s not good practice to install webpack globally, but my solution requires it.

However, after some time I found this solution, which looks elegant, just what I needed, but it also has one problem. I don’t understand completely, how it works.

That my version of how everything operates.

  1. Docker reorders volume mounting based on container paths

  2. Docker mounts sub dir volume at first

  3. Docker mounts parent dir volume but due to an unexplained mechanism, it does not override the sub dir volume…

  4. ???

  5. PROFIT. node_modules dir is in place and webpack runs perfectly.

So, I really want to understand how it actually does all of this black magic. Because without this knowledge I feel like I’m missing something important.
So, guys, how it works?
Thanks in advance.

services:
  react-generic-form:
    image: react-generic-form:package
    container_name: react-generic-form-package
    build:
      dockerfile: dev.Dockerfile
      context: ./package
    volumes:
      - "./package:/package"
      - "/package/node_modules"

Source: StackOverflow