A Brief Guide to Docker Volume

What is a Docker Volume ?

In the simplest form, Docker Volumes are files or directories that are stored on the host file system outside the Docker Container.

Why do we need Docker Volumes ?

A Docker Container begins from the image definition every time it starts. Containers can create, update, and delete files but all these changes are lost when the container is removed. This is where Docker Volumes come to our aid.

How does Docker Volume Persist Data ?

In this article we learnt how to run an app via Docker Container. Here the todo app stores it's data in a SQLite Database at /etc/todos/todo.db . By creating a volume and attaching/mounting it to the directory where the data is stored in, we can persist the data. While our container writes to the todo.db file, it will also be persisted to the host in the volume.

Practical example using Docker Volume

Let's get started...

  1. Stop and remove all the todo app running Containers if any
    docker ps                           --lists current active containers
    docker rm -f <container id>
    eg. docker rm -f container1
    
  2. Create a Docker Volume
    docker volume create volume_name
    eg. docker volume create volume mysql-db
    
  3. Start the docker container

    docker run -dp port1:port2 -v volume_name:database_directory image_name
    eg. docker run -dp 3000:3000 -v mysql-db:/etc/todos node-image
    

    where -v specifies the volume to be used. The volume is mounted to /etc/todos where it will capture all the files that are created at this path.

  4. Open up the app in the browser using http//:localhost:3000. Add some items in the todo list. Now stop and remove the container by repeating step 1

  5. Now start a new container using step 3. When you open the todo list on http//:localhost:3000 , you will see the items you added at step 4. And that's how we persist data in Docker.

docker sqlite.PNG

That's the end of this article. There are plenty Docker Volume commands and concepts to be learnt. This was just a basic overview. Hope this was helpful.

Feel free to leave your suggestions and feedback.

Thank You!