Docker Volumn

Docker Volumn

  • Volume is simply a directory inside our container.

  • Firstly, we have to declare this directory as a volume and then share volume.

  • Even if we stop the container we can still access Volume.

  • Volumn will be created in one container.

  • You can declare a directory as a volume only while creating a container,

  • You can't create a volume from an existing container.

  • You can share any number of columns from any number of containers.

  • The volume will not be included when you update an image.

You can map volume in two ways ->

  1. Container ---> Container

  2. Host ---> Container

Connect Host to a Container

  • First, clone your project to your directory/device.
 git clone https://github.com/CoolSrj06/django-todo-cicd.git
  • Create an image from the Docker file given by the Developer.
docker build . -t django-app
  • Create a directory on your system where you want to create your volume.
mkdir -p volumes/django-app-volumes
cd volumes/django-app-volumes/
  • Create a volume in this directory.
docker volume create --name django--app-volume --opt type=none --opt device=/home/ubuntu/doker_projects/volumes/django-app-volumes --opt o=bind

# docker volume create: command to create a volume
# --name <name of the volume>
# --opt means option
# type=none : it's set to "none", which means that the volume is not being managed by Docker directly. Instead, you're going to manually manage the volume with specific options.
# --opt device=<Location name> 
# --opt o=bind : This option indicates that the volume will be bound to a specific directory on the host filesystem.
  • Run a docker container and also connect your volume with that.
docker run -d --mount source=django--app-volume,target=/data -p 8000:8000 django-app:latest
# This option specifies that a volume named "django--app-volume" (created previously) should
# be mounted into the container at the path "/data". This means that the data stored in the
# host directory associated with the volume will be accessible from within the container at
# the "/data" path.
  • This connects your volume to your container, now whatever you do will be constantly backed up.

Benefits of Volume

  1. Decoupling container from storage.

  2. Share volume among different containers

  3. Attach the volume to containers

  4. On deleting the container volume does not delete.

Some other Commands

docker volume ls
docker volume create <volume name>
docker volume rm <volume name>
docker volume prune # to remove all unused docker volume
docker volume inspect <volume name>
docker container inspect <container name>