This article is written for docker beginners to understand bind mounts and volumes and how to choose between them.
Bind mounts
- A file or directory on the host machine is mounted into a container, it is created on demand if it does not yet exist
- If you bind-mount to a non-empty directory in the container, that directory’s existing contents will be obscured by your directory on the host file system
- Changes in the local directory will propagate to the bind-mounted directory in the container
- Changes in the bind-mounted directory in the container also will propagate back to the local directory
Volumes
- A new directory is created within Docker’s storage directory on the host machine, and Docker manages that directory’s contents
- If you expose a container directory as a volume, its contents are copied into the volume on the host
- Volumes are often a better choice than persisting data in a container’s writable layer, because a volume does not increase the size of the containers using it
- Volumes are easier to back-up or migrate than bind mounts and can be more safely shared among multiple containers
How to Choose
They can be used in different situations. While both options offer a way to data persistence, I would suggest using volumes over bind mounts in normal situations as they are more stable to work with and support more functionalities. But if you are developing a system where you want to easily edit files on the local file system, bind mounts are more convenient in doing that.