Volumes are the preferred mechanism for persisting data generated by and used by Docker containers. While bind mounts are dependent on the directory structure and OS of the host machine, volumes are completely managed by Docker.
- Volume is simply a directory inside own container.
- Firstly , we have to declare this directory as a Volume and then share Volume.
- Even if we stop container, still we can access volume
- Volume will be created in one container
- You can declare a directory as a volume only while creating container
- You can't create volume from existing container
- You can share one volume across any number of containers.
- Volume will not be included when you update an image
- You can mapped volume in two ways:
• container <-> container
• Host <-> container.
Benefits of Volume
- Decoupling container from storage
- Share volume among different container
- Attach volume to container
- on deleting container volume does not delete
Creating Volume from DOCKERFILE
-> create a dockerfile
FROM ubuntu
VOLUME ["/myvolume1"]
-> Then create image from this dockerfile
docker build -t myimage .
-> create a container from image & run
docker run -it --name container1 myimage /bin/bash
-> Then do ls, you can see myvolume1
-> Now share volume with another container
container1 <-> container2
docker run -it --name container2(new) --privileged=true --volumes-from container1(old) ubuntu /bin/bash
-> Now after creating container2, myvolume1 is visible whatever you do in one volume, can see from other volume
touch /myvolume1/samplefile
docker start container1
docker attach container1
ls/myvolume1
-> now you can see samplefile here
Now try to create volume by using command
- docker run -it --name conatiner3 -v /volume2 ubuntu /bin/bash
do ls -> cd /volume2
Now create one file cont3file and exit
Now create one more container and share volume2
- docker run -it --name container4 --privileged=true --volumes-from container3 ubuntu /bin/bash
Now you are inside container; do ls, you can see volume2
Now create one file inside this volume and then check in container3 you can see that file
Now how to create volume (HOST <-> container)
verify files in /home/ec2-user
- docker run -it --name hostcont -v /home/ec2-user:/right --privileged=true ubuntu /bin/bash
- cd /rajput
do ls , now you can see all files of host machine
- touch rajputfile (in container)
- exit
Now check in ec2 machine , you can see this file
Some Other Important Commands.
- docker volume ls
- docker volume create <volumename>
- docker volume rm <volumename>
- docker volume prune {It removes all unused docker volumes}
- docker volume inspect <volumename>
- docker container inspect <containername>