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:

  • Syn flood and net.ipv4.tcp_syncookies
  • Docker shared volume creation
  • Error when loading hortonworks docker image
  • Docker: Is running tests of a windows product on linux container good?
  • docker-compose postgres customize database details
  • What is the different between putting a separate service discovery and integrate it into the cluster machine in Docker Swarm
  • 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!

  • How to access my docker container (Notebook) over the Internet. My host is running on Google Cloud
  • Docker access container logs from the host machine
  • Docker - one process per container?
  • “Cannot connect to the Docker daemon.” error while building docker image in gitlab-ci docker executor
  • AWS ECS container logs design pattern
  • What is a Docker tag (looking for a definition)?
  • 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/*'
    Docker will be the best open platform for developers and sysadmins to build, ship, and run distributed applications.