Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Mounting a volume inside docker container
Docker volumes provide a way to create shared storage that persists beyond the lifecycle of individual containers. When you have multiple containers that need to share common files, mounting a volume allows all containers to access and modify the same data from a centralized location.
This approach is particularly useful in microservices architectures where different containers handle different parts of an application but need to share configuration files, logs, or data files. By mounting a volume to multiple containers, you create a shared filesystem that remains available even when individual containers are stopped or removed.
Creating and Managing Docker Volumes
First, check existing volumes on your system −
sudo docker volume ls
Create a new named volume −
sudo docker volume create tutorialspoint
Inspect the volume details to see its configuration −
sudo docker volume inspect tutorialspoint
Mounting Volume to First Container
Create and run the first container with the mounted volume −
sudo docker run -it -v tutorialspoint:/sharedVol --name container01 ubuntu
The -v flag mounts the tutorialspoint volume to the /sharedVol directory inside the container. The -it flags provide an interactive terminal session.
Inside the container, create a test file in the shared volume −
ls cd /sharedVol echo "Welcome to docker tutorialspoint" > dockertutorials.txt ls exit
Accessing Volume from Second Container
Create another container and mount the same volume −
sudo docker run -it -v tutorialspoint:/sharedVol --name container02 ubuntu
Verify that the file created in the first container is accessible −
cd sharedVol ls cat dockertutorials.txt exit
Volume Persistence After Container Removal
Remove both containers to demonstrate volume persistence −
sudo docker rm -f container01 container02 sudo docker ps -a
Create a new container and mount the same volume −
sudo docker run -it -v tutorialspoint:/sharedVol --name container03 ubuntu
The shared file still exists, demonstrating volume persistence −
ls cd sharedVol ls cat dockertutorials.txt
Key Benefits
| Feature | Benefit |
|---|---|
| Data Persistence | Volume data survives container removal |
| Shared Access | Multiple containers can read/write same data |
| Performance | Better I/O performance than bind mounts |
| Backup | Volumes can be easily backed up and restored |
Conclusion
Docker volumes provide persistent, shared storage for containerized applications. By mounting volumes to multiple containers, you can create a shared filesystem that persists beyond individual container lifecycles, making it ideal for data sharing and backup scenarios in distributed applications.
