Prune unused Docker data without removing volumes
In the previous step, we saw that docker system prune
by default does not remove volumes. Volumes are used to persist data generated by and used by Docker containers. Removing volumes unintentionally can lead to data loss.
In this step, we will demonstrate how docker system prune
works without removing volumes. We will create a volume, run a container that uses it, stop the container, and then prune the system. We will observe that the volume remains after pruning.
First, let's create a named volume. Named volumes are explicitly created and managed by Docker.
docker volume create myvolume
You should see the name of the created volume as output.
Now, let's run a simple container that uses this volume. We will use the ubuntu
image. If you don't have it locally, Docker will pull it.
docker run -d --name mycontainer -v myvolume:/app ubuntu sleep 60
This command runs an ubuntu
container in detached mode (-d
), names it mycontainer
, mounts the myvolume
to the /app
directory inside the container, and keeps the container running for 60 seconds using the sleep 60
command.
Check that the container is running:
docker ps
You should see mycontainer
listed.
Now, stop the container:
docker stop mycontainer
The container will stop, but it will still exist in an exited state.
Verify the container is stopped:
docker ps -a
You should see mycontainer
with a status of "Exited".
Now, let's list the volumes:
docker volume ls
You should see myvolume
listed.
Now, run docker system prune
again. Remember, by default, it doesn't remove volumes.
docker system prune -f
Observe the output. It should indicate that the exited container was removed, but it should not mention removing the volume.
Verify that the container is gone:
docker ps -a
The mycontainer
should no longer be listed.
Finally, verify that the volume still exists:
docker volume ls
You should still see myvolume
listed. This confirms that docker system prune
by default preserves volumes.