How to Share Volume Between Docker Containers Easily
To share a volume between containers, create a Docker volume with
docker volume create and then mount it in each container using the -v volume_name:/path/in/container option. This allows containers to read and write to the same storage space.Syntax
Use the docker volume create volume_name command to create a named volume. Then, start containers with the -v volume_name:/container/path option to mount the volume inside each container.
This syntax lets multiple containers share the same data directory.
bash
docker volume create my_shared_volume docker run -d -v my_shared_volume:/data --name container1 alpine sleep 1000 docker run -d -v my_shared_volume:/data --name container2 alpine sleep 1000
Example
This example creates a shared volume and runs two Alpine containers mounting it at /data. Files created by one container in /data will be visible to the other.
bash
docker volume create shared_vol
docker run -it --rm -v shared_vol:/data --name writer alpine sh -c "echo 'Hello from container1' > /data/message.txt"
docker run -it --rm -v shared_vol:/data --name reader alpine cat /data/message.txtOutput
Hello from container1
Common Pitfalls
- Not creating the volume before using it causes Docker to create an anonymous volume, which is not shared.
- Mounting the volume to different paths in containers can cause confusion.
- Using bind mounts (host paths) instead of volumes can cause permission issues.
Always create and name your volume explicitly and mount it consistently.
bash
docker run -d -v /data alpine sleep 1000 # Incorrect syntax, missing container path docker volume create shared_vol docker run -d -v shared_vol:/data alpine sleep 1000 # Correct shared volume usage
Quick Reference
Remember these key points when sharing volumes:
- Create a named volume first with
docker volume create. - Mount the volume in all containers at the same path.
- Use volumes for data sharing, not anonymous or host bind mounts unless needed.
Key Takeaways
Create a named Docker volume before using it to share data.
Mount the same volume in multiple containers at the same path.
Avoid anonymous volumes if you want data sharing between containers.
Use volumes instead of host bind mounts to prevent permission issues.
Consistent volume paths in containers avoid confusion and errors.