Pages

Tuesday, July 25, 2023

Docker Volumes

Docker Volumes


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. Volumes have several advantages over bind mounts:

-Volumes are easier to back up or migrate than bind mounts.
-You can manage volumes using docker CLI commands or the docker API.
-Volumes work on both Linux and Windows containers.
-Volumes can be more safely shared among multiple containers.
-Volume drivers let you store volumes on remote hosts or cloud providers, to encrypt the contents of volumes, or to add other functionality.
-New volumes can have their content pre-populated by a container.
-Volumes on docker Desktop have much higher performance than bind mounts from Mac and Windows hosts.

=> We have 3 types of volumes in docker

1) Anonymous Volume ( No Name )
2) Named Volume
3) Bind Mounts


1) Anonymous volumes are created if the Dockerfile declares a path as VOLUME, but neither a volume, nor a bind is mapped into this path for a container instance of this image. This is the result of the design choices an image maintainer did for their image and your choice to not mount anything into that path.

2) Named volumes are volumes which you create manually with docker volume create VOLUME_NAME. They are created in /var/lib/docker/volumes and can be referenced to by only their name. Let's say you create a volume called "mysql_data", you can just reference to it like this docker run -v mysql_data:/containerdir IMAGE_NAME.

3) Bind mounts are basically just binding a certain directory or file from the host inside the container
(docker run -v /hostdir:/containerdir IMAGE_NAME)


# List or display docker volumes?
$ docker volume ls

# How to create Docker Volume?
$ docker volume create <vol-name>

# How to check the details of docker volume?
$ docker volume inspect <vol-name>

# How to remove docker volume?
$ docker volume rm <vol-name>

# How to remove all volumes
$ docker system prune --volumes


DEMO:

To create a Docker Volume use the command

docker volume create qadervol1
docker volume 1s
docker volume inspect qadervol1


Mounting a Volume using -v or --mount

docker run -it --name=server01 --mount source=qadervol1,destination=/data centos
docker run -it --name server04 -v qadervol1:/data centos
docker run -it --volumes-from server01 --name server02 centos /bin/bash


Mounting a host directory as a data volume?

mkdir files
cd files
docker run -it --volumes-from server01 --name server02 centos /bin/bash
touch file.txt
docker run -it -name server04 -v "$(pwd)":/datal centos




No comments:

Post a Comment