How to persist data in Docker Volume?

Salman Khan
2 min readDec 13, 2020
Photo by Dominik Lückmann on Unsplash

What is docker?

Docker is a software platform that allows you to build, test, and deploy applications quickly. Docker packages software into standardized units called containers that have everything the software needs to run including libraries, system tools, code, and runtime.

What happens when we stop and run the new container?

Docker creates its own environment when we run any container. Data that we upload in our running application goes into the virtual environment. So once we build a new image and run it, the data which are stored in the previous containers will lose their reference and we can no longer see those data.
When I was learning Docker then at that time I got confused about where my data went. After doing R&D I got to know about Docker Volumes.

What are Docker Volumes?

Docker volumes are just folders that contain data that is generated by and used by containers. Default location for Docker Volumes are /var/lib/docker/volumes. To persist our data into these volumes we need to give reference to these volumes while running the docker container.

How to run docker using volume?

  • First, create the volume by firing the below command
docker volume create volume-name
  • To get the path where your volume resides type docker inspect volume volume-name. You will get the below data in your terminal where “Mountpoint” is the path which we are looking for.
[
{
"CreatedAt": "2020-12-13T14:15:39Z",
"Driver": "local",
"Labels": {},
"Mountpoint": "/var/lib/docker/volumes/hello/_data",
"Name": "hello",
"Options": {},
"Scope": "local"
}
]
  • I have used Docker with .net core always and to build my image I typedocker build -t “image-name” — file Dockerfile .
  • Now our main and final step is to map the volume with our container. To map it fire the below command
docker run -it -d -p 0.0.0.0:80:80 -v /var/lib/docker/volumes/ volume-name /_data:/app/wwwroot/images/ image-name
  • -v in the above command is the volume command which maps our volumes folder(refer to point 2 for path) with the container folder where our data gets stored inside the containers. For e.x: /app/wwwroot/ is the default folder in .net core where all our static files goes.

Note: To check your data inside volumes navigate to the volume path and you will see your data that you upload on your application.

If you found this article helpful then please clap it. Your each clap matters a lot ❤️ to me.

--

--

Salman Khan

Full Stack Software Developer | Entrepreneur | Community Believer