How do you remove the contents of a docker volume?
I have a volume created from a docker-compose.yml file. Let’s call the volume my_volume and the container it’s associated with my_container. I want to script the removal of the contents of the volume. All of the below assumes that my_container has been stopped, but not removed.
I can list the contents of the volume using:
docker run --rm -v my_volume:/data/ ubuntu ls -la /data
This works, so next I try to remove the contents of the data folder using:
docker run --rm -v my_volume:/data/ ubuntu rm -rf /data/*
No error message is reported so things appear successful, but when I list the contents of the volume again, none of the data in the volume has been removed.
I can accomplish the removal by entering a container and then doing the removal like so:
docker run --rm -it -v my_volume:/data/ ubuntu /bin/bash
then from within the container:
rm -rf /data/*
This works fine and the contents are removed, but this defeats the purpose since it’s not scriptable. Any ideas why rm does not work when I try to use it outside of the container and how I might go about removing the contents of the volume successfully? I should note that I don’t want to remove the volume and create a new one as doing so requires removing the original container/image associated with the volume which I don’t want to do. Thanks for any help!
One Solution collect form web for “How do you remove the contents of a docker volume?”
Any ideas why rm does not work when I try to use it outside of the container
I believe what is happening is that
/data/* is being evaluated in the host shell. So the container is actually being run with the command
rm -rf /data/somefile /data/otherfile ... with the list of files in the
/data directory on the host. If those files don’t match the container then it will appear to not have removed anything.
You can use single quotes to prevent the expansion from happening in the host shell.
rm -rf '/data/*'