Bind mounts in Docker allow you to map a file or directory on the host machine to a file or directory in a container. This can be useful for development and testing, as any changes made to the host file or directory are immediately reflected in the container.
There are two ways to use bind mounts in Docker: using the -v
flag or the --mount
flag. The -v
flag combines all the options together in one field, while the --mount
flag separates them. The --mount
flag is more explicit and verbose, and is recommended for new users.
Here is an example of using the --mount
flag to create a bind mount:
docker run --mount type=bind,source=/path/on/host,target=/path/in/container my-image
In this example, /path/on/host
is the path to the file or directory on the host machine, and /path/in/container
is the path where the file or directory is mounted in the container.
By default, bind mounts are read-only. To allow writes on the mount, you can use the rw
or readwrite
option:
docker run --mount type=bind,source=/path/on/host,target=/path/in/container,rw my-image
It is also possible to use bind mounts with Docker services. When creating a service, you can use the --mount
flag to specify the bind mount options. For example:
docker service create --mount type=bind,source=/path/on/host,target=/path/in/container my-service
It is important to note that bind mounts rely on the host machine’s filesystem having a specific directory structure available. If you are developing new Docker applications, it is recommended to use named volumes instead.
For more information, see the following resources:
- Bind mounts | Docker Docs
- Dockerfile reference | Docker Docs
- docker service create | Docker Docs
- Manage data in Docker | Docker Docs
- File Sharing with Docker Desktop | Docker
- User-guided caching in Docker for Mac | Docker
- Volumes | Docker Docs
- How To Use minikube for Local Kubernetes Development and Testing | DigitalOcean