DEV Community

Cover image for Docker Volume and how to share it.
Pranjal-Agrawal
Pranjal-Agrawal

Posted on

Docker Volume and how to share it.

Docker is a common containerization solution that offers a user-friendly interface. It allows you to deploy your application as a lightweight process set rather than a complete virtual machine.

Docker Volume:-

A Docker volume is an independent file system entirely managed by Docker and exists as a normal file or directory on the host, where data is persisted.

  • Volume is simply a directory made inside our container.

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

  • We can declare a directory as a volume only while creating container.

  • Cannot create volume for existing container.

  • Can share the volume across any number of containers.

Benefits of Volume:-

  • Decoupling container from storage.

  • Share it among different containers.

  • On deleting the container the volume does not get deleted.

We can map volume in two ways:-

  1. Container <-> Container

  2. Host <-> Container

Created an EC2 Instance-
Image description

Then ssh into the instance-

Image description

CREATING VOLUME FROM DOCKER FILE AND MAPPING IT TO ANOTHER CONTAINER:-

sudo su

yum update -y

Install the Docker:-

yum install docker -y

Image description

Create a Docker file:-

vi Dockerfile

Image description

Write the following inside the Dockerfile

Image description

Then create the image from this Dockefile:-

Image description

Now create a container with the name cont1 from the image and run:-

Image description

Create some files in it:-

Image description

Now to share the volume with another container, create a container with a name cont2:-

Image description

After creating the cont2, the volume from cont1 would be visible and any changes made in that volume will be visible to both the containers.

Image description

Image description

_CREATING THE VOLUME USING COMMAND:-
_
Create a new container with name cont3

Image description

Create a new container with the name cont4 and share the volume with it.

Image description

Create some files inside it and see its present in both the containers.

Image description

SHARING VOLUME HOST <-> CONTAINER:-

Verify the files in the /home/ec2-user and run the following command -

Image description

Go to that directory and do ls

Image description

Create some files in the container in that particular directory

Image description

Now check in the EC2 host machine and we can see the files we created now.

Image description

Top comments (0)