How to Use docker run -v for Volume Mounting
Use
docker run -v host_path:container_path to mount a directory or file from your host machine into the Docker container. This lets the container access or save data directly on your host, making data persistent or shared.Syntax
The -v option in docker run mounts a volume from the host to the container. The syntax is:
host_path:container_path- Mounts a directory or file from the host to the container.ro(optional) - Mounts the volume as read-only.
bash
docker run -v /path/on/host:/path/in/container image_name
Example
This example mounts the host directory /home/user/data into the container at /app/data. The container can read and write files in this folder, and changes persist on the host.
bash
docker run -it -v /home/user/data:/app/data ubuntu bash
Output
root@container_id:/# ls /app/data
file1.txt file2.txt
Common Pitfalls
Common mistakes include:
- Using relative paths instead of absolute paths on the host.
- Forgetting to create the host directory before mounting.
- Not specifying
rowhen you want a read-only mount. - Permission issues if the container user cannot access the host directory.
bash
docker run -v data:/app/data ubuntu # Wrong: 'data' is a named volume, not a relative path
docker run -v /home/user/data:/app/data:ro ubuntu # Right: mounts read-onlyQuick Reference
| Option | Description | Example |
|---|---|---|
| -v host_path:container_path | Mount host directory/file into container | docker run -v /host/data:/container/data ubuntu |
| -v host_path:container_path:ro | Mount as read-only | docker run -v /host/data:/container/data:ro ubuntu |
| -v volume_name:container_path | Use named Docker volume | docker run -v myvol:/app/data ubuntu |
Key Takeaways
Always use absolute paths for the host directory when using -v.
Mounting volumes shares files between host and container for persistence or data sharing.
Add :ro to mount volumes as read-only to protect host data.
Create host directories before mounting to avoid errors.
Check permissions to ensure the container can access the mounted path.