Docker volume
What is a Docker Volume?
In simple terms, a Docker Volume is a designated directory on the host machine which bypasses the Union File System, used to store and manage data in Docker. This directory becomes a reference point for Docker to save and retrieve data.
Docker Volumes offer three key benefits:
Data Persistence: Even if the container shuts down, the data remains.
Data Sharing: Multiple containers can share access to a single volume.
Performance: Volumes offer better I/O performance as compared to Docker containers.
First make a directory outside your code, and then give a fole name like — Volume and then inside this you can make a folder name where your app all data store. for example — mkdir -p volume/django_app_volume
To show docker volume in your system
docker volume ls
create docker volume
docker volume create --name <volume_name> --opt type=none --opt device=/home/ubuntu/project/volumes/django-todo-volume --opt o=bind
docker volume create --name <volume_name> --opt type=none --opt device=/home/ubuntu/project/volumes/django-todo-volume --opt o=bind
show all detail about your docker volume
docker volume inspect <volume_name>
To mount your docker volume to your system
you need to run this cmd inside where you create a volume -
docker run -d --mount source=<volume_name>,target=/data(WORKDIR) -p 8000:8000 <image_name>:latest(img_tag)
Now you can see same file and folder in your new volume creare directory.
Now go inside the container shell and create a file
docker exec -it <container_id> sh
touch <file_name>
echo "test@123" > <file_name>
exit
after comming outside the container shell you can see a new file created same as created in your container shell. now if you delete your container and after recreate a new container all data store in you new container shell.
practicle:-
1. Mount Host Project Folder to Container :-
install docker and give permission
sudo chown $USER /var/run/docker.sock
create dockerfile
. and build docker image
share data between host to container without creating docker volume by directly mounting host directory to container directory.
docker run --name <contanier_name> -itd -v <host/dir>:</container/dir.> <img>:<tag>
docker exec -it <container_name or ID> bash
ex:-
docker run --name python-c -itd -v /home/hemant/devops/docker/volume:/app python:3.9-slim
docker exec -it python-c bash
docker volume create myvol
docker volume ls
docker volume instpect myvol
docker volmue remove (after detched conatainer)
docker run --name c1 -itd -v myvol:/app python
docker run --name c2 -itd -v myvol:/app1 python
docker ps docker exec -it bash