In this post we will see how to use a Volume in a Docker container.
First of all, what is a Volume and when we need it?
A Docker image is made of a set of read-only layers and when we start a new container, Docker takes the read-only image and adds a read-write layer on top. The problem is that when the container is stopped or deleted, that read-write layer is lost.
In order to be able to save data we can use ‘Volumes’.
In a nutshell, Volumes are directories (or files) that are outside of Container and exist as normal directories and files on the host filesystem. In this way, when Container is stopped or deleted, we will not lose any data.
Now, we will see how to use a Volume in a MongoDB container.
We start running a MondoDB container using the command:
docker run -d -–name dockermongo mongo
Then, using the command docker exec -it dockermongo bash, we will execute the bash command inside the container, in order to manage the instance of MongoDB:
Finally, we will create a database called testdb where we will add a collection called Users with two items:
Now, we stop and delete this container:
and then, we will create a new container where we will check if the “testdb” database is still present:
We can see that “testdb” does not existing and the reason is because we have deleted the previous container.
In order to fix this problem, we will create a new container with a volume called “volumetestdb”, using the command:
docker run -d --name dockermongo -v volumetestdb:/data/db mongo
Now, we will create the “testdb” database where we will add a collection called Users and then, we will destroy the container.
After this, we will create a new container, using the same volume, and we will verify if “testdb” database still exists.
CREATION OF ‘TESTDB’ DATABASE
CONTAINER DELETION
CREATION OF A NEW CONTAINER USING THE PREVIOUS VOLUME
CHECKING DB
We can see that using a volume the “testdb” database still exists and nothing was lost.
Finally, two commands that can help us to manage volumes:
LIST VOLUMES
DELETE VOLUME