Table of contents
Imagine we rolled a docker container and made some files but due to unfortunate circumstances, it got deleted. What do you do now? It's lost. So now you comes the role of Docker Volumes.
You basically connect the respective directory of a particular container that you want to save with the folder directory of your local system, so the data would be preserved even if the container is deleted. Thus in laymen terms you could say a linkage is formed.
Attaching Host Volumes
Example:
docker run -d --name devtest -v myvol2:/app nginx:latest
-d
: Runs the container in detached mode (in the background).--name devtest
: Assigns the name "devtest" to the container.-v myvol2:/app
: Mounts the local volume "myvol2" to the "/app" directory inside the container.nginx:latest
: Specifies the "nginx" image with the latest version as the base image for the container.
Use docker inspect devtest
to verify that Docker created the volume and it mounted correctly. Look for the Mounts
section:
"Mounts": [
{
"Type": "volume",
"Name": "myvol2",
"Source": "/var/lib/docker/volumes/myvol2/_data",
"Destination": "/app",
"Driver": "local",
"Mode": "",
"RW": true,
"Propagation": ""
}
],
This shows that the mount is a volume, it shows the correct source and destination, and that the mount is read-write.
Stop the container and remove the volume. Note volume removal is a separate step.
$ docker container stop devtest
$ docker container rm devtest
$ docker volume rm myvol2
Use docker volume
to see the list of docker command available.
Attaching Custom Volumes
Instead of creating a new directory on your local system and manually attaching it as a volume to the container, Docker provides a convenient way to create custom volumes that are automatically stored within the Docker system file directory on your system. These custom volumes can then be easily used without specifying a particular directory when connecting to other containers.
To create a custom volume, you can use the following Docker command:
docker volume create mycustomvolume
Once created, you can connect this custom volume to a container using the -v
flag:
docker run -it --name mycontainer -v mycustomvolume:/app nginx:latest
By specifying the custom volume (mycustomvolume
) instead of a specific directory, you ensure that the volume is automatically mounted within the container's /app
directory. This allows seamless data sharing and persistence between containers without the need for manual directory management.
Thanks a lot for reading the article.
Hope you found it helpful.
My linkedin: https://www.linkedin.com/in/tautikk/
My Email: tautikagrahari@gmail.com