2

Here are the docker layers I want to implement: https://stackoverflow.com/questions/31222377/what-are-docker-image-layers

I want to mount a folder from host to docker with:

docker run \
-v /path/to/host/large_size_folder:/var/large_size_folder \
my_docker \
/bin/bash -c "rm -rf /var/large_size_folder/file1 && echo "hello" > /var/large_size_folder/file2"

Because the size of /path/to/host/large_size_folder is very large that I don't want to copy it to the docker image. So I use -v to mount it to the docker image.

And then, I run the docker and use bash to add/modify/delete files inside the "/var/large_size_folder".

But this action will also add/modify/delete files from host.

Is it possible to make any modification in the docker layer only without affecting the host directory when running /bin/bash -c "rm -rf /var/large_size_folder/file1 && echo "hello" > /var/large_size_folder/file2" inside the docker container?

terdon
  • 104,119
stackbiz
  • 495

1 Answers1

1

You could implement a solution by manually adding an overlayfs (which Docker also uses internally to manage volumes), so that changes to the filesystem are written to a separate directory, and can be undone at any time.

So set up the following: (create the directories - you can change the location of these as you see fit)

  • /path/to/host/large_size_folder (already exists) is the lower layer directory in the overlayfs, containing the original data (will not be modified)
  • /tmp/large_size_folder_changes is the upper layer directory where modifications will be stored
  • /tmp/overlayfs is the working directory for overlayfs (internal directory needed for overlayfs to work)
  • /mnt/large_size_folder_merged is the merged directory where we can access the combined content, and this is what you want to map into the Docker container

The command to mount the overlayfs is then:

sudo mount -t overlay overlay -olowerdir=/path/to/host/large_size_folder,upperdir=/tmp/large_size_folder_changes,workdir=/tmp/overlayfs /mnt/large_size_folder_merged

And then to create your Docker container, instead use:

docker run \
-v /mnt/large_size_folder_merged:/var/large_size_folder \
my_docker \
/bin/bash -c "rm -rf /var/large_size_folder/file1 && echo "hello" > /var/large_size_folder/file2"

Now any changes you make to /var/large_size_folder inside the container will be reflected in /mnt/large_size_folder_merged on the host.

The changes only can be seen inside /tmp/large_size_folder_changes, while the original /path/to/host/large_size_folder remain unchanged.

Also see here for: How do I use OverlayFS?

Artur Meinild
  • 31,035