Managing Volumes
Auto-Creation of Volumes
What happens if you try to start a container and attach it to a volume that doesn’t exist?
# Assuming 'new-vol' doesn't exist
docker run -d -p 3001:2368 -v new-vol:/var/lib/ghost ghost
It turns out the -v new-vol:/var/lib/ghost flag will bind to a new-vol volume if it exists, but otherwise, it creates it automatically!
Deleting Volumes and Cleaning Up
When you’re done, you’ll want to save space on your host machine by deleting the volume and the container.
- First, use
docker ps -ato see all containers (even stopped ones). - Stop and remove the containers using
docker stopanddocker rm. - Use
docker volume lsto find your volumes. - Remove the volume using
docker volume rm.
# Stop and remove container
docker stop CONTAINER_ID
docker rm CONTAINER_ID
# Remove the volume
docker volume rm my-vol
Note: You cannot remove a volume that is currently in use by a container, even if the container is stopped. You must remove the container first.