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-compose nginx volumes not mounted
  • Are there disadvantages when running a docker base image that differs from my distribution?
  • Can't set shell variable in Dockerfile
  • How to log all the processes running inside a Docker container?
  • HTTPS request from Docker container to LAN IP fails, but curl works
  • How could I enable docker remote api on mac osx
  • 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!

  • Networking and DNS in Kubernetes local cluster with Docker
  • Virtualbox port forwarding with docker
  • Docker compose connection issue
  • Can docker application use dependent images?
  • Docker and Kubernetes repository for linux
  • Docker Disable legacy registry using osx
  • 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.