How to mount volume on docker-compose but keep existing subfolder from image?

Viewed 783

I have a node project and my docker image already has the dependencies installed.

I want to run docker-compose with my project folder to be in sync with the container's folder so I can edit local files and they should change inside the container.

BUT I want to keep whatever content there was inside image's node_modules folder.

I know this question tells me how to ignore a subfolder when mounting a volume, but that will erase the dependencies that were already installed.

Is there any way to mount my project's folder but keep the container's node_modules subfolder?

2 Answers

Try this

Dockerfile

...
RUN mkdir -p /app/node_modules
VOLUMES /app/node_modules
VOLUMES /app
EXPOSE XX
...

Project structure

project/
|--node_modules/
|----...
|--docker_node_modules/
|----...
|--docker-compose.yml
|--...

Docker run command

docker run --it --rm \
    -p xx:xx \
    -v /host/path/project/docker_node_modules:/app/node_modules \
    -v /host/path/project:/app \
    nodeImageExample \
    commandToStartYourNodeApp
  1. From you host when running npm install, it'll be install under ./node_modules (host)

  2. From container when running npm install (container), it'll be install under /app/node_modules (container) and ./docker_node_modules/ (host)

By doing this you have package from your container saved without affecting your node_modules

This solution should work for you :

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

When you first run the project with docker-compose up, the node_modules volume will be created and initialized with the content of the container at /app/node_modules. At subsequent calls, the content of the volume (which already exists) will be preserved.

As explained in the documentation:

If you start a container which creates a new volume, as above, and the container has files or directories in the directory to be mounted (such as /app/ above), the directory’s contents are copied into the volume. The container then mounts and uses the volume, and other containers which use the volume also have access to the pre-populated content.

The content of the node_modules volume can be accessed on your host at /var/lib/docker/volumes/<project>_node_modules/_data/

Related