⭐ Docker Volume

⭐ Docker Volume

Image courtesy: https://miro.medium.com/v2/resize:fit:1200/1*xONk464vW-xNYxzE_HsSkw.png

✔Method 1: Creating volume using a Docker file

  1. Create a dockerfile with the following contents:

     FROM ubuntu  #base image
     VOLUME ["/myvolume"] #creating a volume
    
  2. Run the docker file and create an image

     docker build -t myimage . 
     # creates an image from the dockerfile present in the current directory, "." signifies current directory
    
  3. Create and run a container from the image created:

     docker run -it --name myc1 myimage /bin/bash
    

    We can see a directory named "myvolume" this is the newly created volume.

  4. Now lets create another container "myc2"

    Note: We have to share the volume while creating the container.

     docker run -it --name myc2 myimage --privileged=true --volumes-from myc1 ubuntu /bin/bash
     #specify new container name, image name, volume from which container, base image
    

    Output:

    We can see the volume "myvolume1" here. Lets create some files and then check if they are visible from "myc1" volume.

  5. Running container "myc1" :

    We can see that the files created in container 2 are visible in container 1 and vice versa.

✔Method 2: Creating Volumes directly by commands

  1. Create container with volume using the following command:

     docker run -it --name myc3 -v /volume2 ubuntu /bin/bash
     #myc3- container name
     #volume2 - volume name
    

  2. Run the command for creating container 4 and sharing the volume created in container 3:

    We can see that files created in the volume are visible in container 4 as well.


✔Volumes: Host to Container

In my case I have installed Docker on EC2 instance so host is EC2 instance

Lets share volumes between container and host:

docker run -it --name host_container -v /home/ec2-user:/akshata --privileged=true ubuntu /bin/bash
# /home/ec2-user is the host directory and "akshata" - name of directory inside container

Output:

We can see files created in ec2-user directory are visible in the container and vice-versa.


Thus we have learned how to create volumes in 2 ways, through Docker file as well by the command line.

Let me know if you have any feedback, suggestions or questions. Feel free to reach out. Thank you!