How to mount a host directory into a running docker container

妖精的绣舞 提交于 2021-01-28 03:27:04

问题


I want to mount my usb drive into a running docker instance for manually backup of some files.

I know of the -v feature of docker run, but this creates a new container. Note: its a nextcloudpi container.


回答1:


You can only change a very limited set of container options after a container starts up. Options like environment variables and container mounts can only be set during the initial docker run or docker create. If you want to change these, you need to stop and delete your existing container, and create a new one with the new mount option.

If there's data that you think you need to keep or back up, it should live in some sort of volume mount anyways. Delete and restart your container and use a -v option to mount a volume on where the data is kept. The Docker documentation has an example using named volumes with separate backup and restore containers; or you can directly use a host directory and your normal backup solution there. (Deleting and recreating a container as I suggested in the first paragraph is extremely routine, and this shouldn't involve explicit "backup" and "restore" steps.)

If you have data that's there right now that you can't afford to lose, you can docker cp it out of the container before setting up a more robust storage scheme.




回答2:


As David Maze mentioned, it's almost impossible to change the volume location of an existing container by using normal docker commands.

I found an alternative way that works for me. The main idea is convert the existing container to a new docker image and initialize a new docker container on top of it. Hope works for you too.

// Create a new image from the container
docker commit CONTAINERID NEWIMAGENAME

// Create a new container on the top of the new image
docker run -v HOSTLOCATION:CONTAINERLOCATION NEWIMAGENAME



回答3:


I know the question is from May, but for future searchers:

Create a mounting point on the host filesystem:

sudo mkdir /mnt/usb-drive

Run the docker container using the --mount option and set the "bind propagation" to "shared":

docker run --name mynextcloudpi -it --mount type=bind,source=/mnt/usb-drive,target=/mnt/disk,bind-propagation=shared nextcloudpi

Now you can mount your USB drive to the /mnt/usb-drive directory and it will be mounted to the /mnt/disk location inside the running container.

E.g: sudo mount /dev/sda1 /mnt/usb-drive

Change the /dev/sda1, of course.

More info about bind-propagation: https://docs.docker.com/storage/bind-mounts/#configure-bind-propagation



来源:https://stackoverflow.com/questions/56209021/how-to-mount-a-host-directory-into-a-running-docker-container

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!