Add a volume to Docker, but exclude a sub-folder

For those trying to get a nice workflow going where node_modules isn't overridden by local this might help.

  1. Change your docker-compose to mount an anonymous persistent volume to node_modules to prevent your local overriding it. This has been outlined in this thread a few times.
services:
  server:
    build: .
    volumes:
      - .:/app
      - /app/node_modules
  1. This is the important bit we were missing. When spinning up your stack use docker-compose -V. Without this if you added a new package and rebuilt your image it would be using the node_modules from your initial docker-compose launch.
    -V, --renew-anon-volumes   Recreate anonymous volumes instead of retrieving
                               data from the previous containers.

If you want to have subdirectories ignored by docker-compose but persistent, you can do the following in docker-compose.yml:

volumes:
  node_modules:
services:
  server:
    volumes:
      - .:/app
      - node_modules:/app/node_modules

This will mount your current directory as a shared volume, but mount a persistent docker volume in place of your local node_modules directory. This is similar to the answer by @kernix, but this will allow node_modules to persist between docker-compose up runs, which is likely the desired behavior.


Using docker-compose I'm able to use node_modules locally, but ignore it in the docker container using the following syntax in the docker-compose.yml

volumes:
   - './angularApp:/opt/app'
   - /opt/app/node_modules/

So everything in ./angularApp is mapped to /opt/app and then I create another mount volume /opt/app/node_modules/ which is now empty directory - even if in my local machine ./angularApp/node_modules is not empty.