Hey gang! Welcome to another exciting “Hello Whale” blog about volumes! Contain yourselves while I break this down 😉🐳
Ok, let’s move past that terrible container pun and continue…
As we’ve talked about before in my previous “Hello Whale” posts, containers are impermanent, and can be quickly and easily created as well as destroyed. But, what about the data in our application we’d like to keep around (for example: a database)?
Ok, not that kind of volume…
Docker came up with the concept of volumes to help us save persistent data and to help us use the same data between different containers. Volumes are files or directories that live outside of the UFC (Union File System) and live on the host filesystem. This makes them separate from the container itself, making it much more difficult to remove on accident. By having this separation of concerns, we are able to create and remove our container freely without worry about our volume data being impacted.
To quote the Docker docs:
Data volumes are designed to persist data, independent of the container’s lifecycle. Docker therefore never automatically deletes volumes when you remove a container, nor will it “garbage collect” volumes that are no longer referenced by a container.
Well said, Docker.
If you’ve seen a DockerFile before, you have likely seen the
VOLUME command. It usually looks like this:
What this is saying is: “when you start a new container, make a new volume location and assign it to this directory in the container”. So, volumes need manual deletion. If you remove a container, the volume will still be there. This extra step protects this data from being destroyed each time we start a new container.
Think of volumes like the baton in a race. With each new lap, the runner changes but the item being passed between them stays consistent.
In this example, the runners are our containers, and the baton (er-drumstick?) is our volume.
When running a container, you can run
docker volume ls to see your running volumes. This will usually spit out an ugly long number/letter combo for it’s “name” that would be pretty impossible to remember… well, lucky for us, Docker has named volumes!
I’m able to name my volume by adding the -v command when I run my container. Here’s an example:
docker run -P --name testing123 -v yay-name:/var/lib/python python
Now, when I run
docker volume ls I’ll see:
DRIVER VOLUME NAME local yay-name
Phew! Much better than something like “50aea75f82f0000964e65331387486432adea497b1548c3bf62387b818c50b0a” 😅
And that’s it! You can create volumes from a
docker container run command, from the Dockerfile, or ahead of time (lookout for a future blogpost on this third method/use case).
I hope this has helped you understand volumes better, and feel free to comment/email me with any additional questions!