If you are working with Docker, you need to know which type of volume to use for your application. There are two main types: Bind Volumes and Named Volumes.
- Bind Volumes (The Two-Way Mirror) Imagine you are building a web app and consistently adding new features. Instead of rebuilding the image every time you update your code, you use a Bind Volume. You attach a folder on your laptop directly to a folder inside the container. If you change the code on your laptop, it automatically reflects inside the container.
Example:
1. Create a folder on your laptop
mkdir -p $(pwd)/laptop-dir
2. Run a container and "Bind" that specific folder
docker run -d --name bind-test -v $(pwd)/laptop-dir:/data alpine sh -c "echo 'Data from Mac' > /data/hello.txt && sleep 1000"
Here
-v: This handles the volume work.
/data: The folder inside the container.
sh -c: This creates a shell to talk to the Linux kernel and run our commands.
sleep 1000: Since a container only runs as long as the main process is alive, we use sleep to give us time to see the file on our laptop before the process ends.
- Named Volumes (The Persistent Vault) For Named Volumes, the Docker engine creates storage internally. You use this for important things like production databases. If a container is deleted, the data usually goes with it—but not if you use a Named Volume. You can simply attach that same storage to a new container.
Example:
1. Create the volume
docker volume create my-sre-vault
2. Use it in a container
docker run -d --name temp-db -v my-sre-vault:/data alpine sh -c "echo 'Hemant was here' > /data/file.txt && sleep 1000"
3. Delete the container
docker rm -f temp-db
4. Prove the data is still there in a new container
docker run --rm -v my-sre-vault:/data alpine cat /data/file.txt
Even after deleting the container, we can still get the data. That is the beauty of a Named Volume—it saves your data even if the container is gone.
The Summary:
Use Bind Volumes for things like source code or files that change often during development.
Use Named Volumes for private, stable things like databases where data persistence is a must.
Top comments (0)