Docker volumes
Docker volumes are used to keep data persistent when the container is restarted or deleted. By default, if the container stops or deletes, all data from the docker is lost.

Assume a mongo database is configured and running on a docker. We have stored a variety of data in the database, but the container of the mongo database has been stopped or removed.

We will be unable to find any data in the database the next time we build or restart the mongo container. And this could result in significant data loss, which would have to be migrated if it was possible.

So Docker volumes come into play to avoid such a catastrophe and make data persistent.

Three different types of Docker volumes exist.

1. Host volumes: This is where the data stored in host machine directly.

2. Anonymous volumes: These are volumes where data is saved in a random directory established by Docker.

3. Named volumes: This is where data is kept in a random directory defined by Docker but with a unique name. This is quite useful, and with the tags attached, it is also very easy to manage.


The -v parameter can be used with the docker run command to define the docker volume.


/data/db is the directory on the container where data is kept for mongo db, and mongo-data is the name of the volume.

And docker generates a directory in the host computer according to the name of the volume, for example inside docker/volumes.

The following commands have been successfully executed and will be checked.

After that, when we go to mongo express on localhost, we can see that the collection and data are still there. When you stop or delete a Docker container, it doesn't get deleted.