Practical Example of Docker Volumes
Let's see a small practical example of how Docker volumes work. We will run a small Ubuntu container:
docker run -it -v /Users/your-username/Desktop/data:/test/data ubuntu
Explanation
-v is the volume flag
/Users/your-username/Desktop/data is the host machine path (our local machine's folder)
/test/data is the container path (where it gets mounted inside the container)
What This Means
This creates a mapping (bind mount) between:
- Host machine folder →
/Users/your-username/Desktop/data
- Container folder →
/test/data
So whatever data is stored inside the container at /test/data is also reflected on the host machine.
Testing the Volume
Inside the container, create two files:
cd /test/data
touch index.html
touch server.js
What Happens Next?
Now check your host machine (Desktop folder):
You will see:
Even though these files were created inside the container, they are now visible on the host machine as well.
Persistence Test
Step 1 — Exit Container
Step 2 — Restart Container
Start the container again:
docker run -it -v /Users/your-username/Desktop/data:/test/data ubuntu
You will still see the same files inside /test/data.
Step 3 — Delete Container
Even if we completely delete the container:
Final Result
Check the host machine folder:
The files are still present:
Key Observation
Even after:
- Stopping the container
- Restarting the container
- Deleting the container
The data still persists on the host system.
Why This Works
Because Docker volumes (bind mounts in this case) store data outside the container filesystem.
So:
Container data → mapped to → Host machine directory
Summary
-v flag is used to create a volume (bind mount)
- Host directory is mapped to a container directory
- Data is shared between host and container
- Data persists even after container deletion
- This is essential for persistent storage in Docker