In Docker all the data is abstracted and stored at container lever. The lifecycle of those data is tightly coupled with container which means as soon as the container is deleted data is lost. This leads us to the need of storage where the data can be persisted outside container lifecycle.
Docker allows this in 3 ways:
- Bind mounts
For volumes, data is stored inside the host’s file system area managed by docker. Usually its
- Volumes are preferred since the storage location is managed by docker
- Volumes can be created explicitly or while creating the container
Volumes can be created using specifying
— -mount flag.
-v flag, there are 3 fields:
- Name of the volume. Anonymous volumes also can be created, in which docker will name it uniquely.
- Path where directory/file is mounted inside the container. e.g. In case of MSSQL its the data path where the data is stored.
- [Optional] Comma separated options list. e.g.
rois given for read only volumes
--mount , there are a list of key value pairs:
source: Name of the volume. Omit this field to create anonymous volume.
destination: path where the file/directory is mounted in the container
type: The value is
Note: The difference between
--mountis that latter is more verbose and hence easy to understand.
Create a volume explicitly
docker volume create <vol_name> // <vol_name> should be replaced by name of volume
Create a volume while spinning up the container
docker run -v <vol_name>:<destination_path> <image>//using --mount
docker run --mount source=<vol_name>,target=<destination_path>,type=volume <image>
Inspect a volume
docker inspect <vol_name>
Remove a volume
docker volume rm <vol_name>
In bind mounts, the data can be stored anywhere in host’s filesystem other than the area managed by docker. While creating the bind mount absolute file path w.r.t host should be given as the source.
Create a bind mount while spinning up the container
docker run --mount type=bind,source=<source_path>,target=<target_path> <image> // <source_path> should be replaced by absolute path. e.g. if the the folder is called target in current working directory, then it should be "$(pwd)"/target.