We’ve already seen how to Install Docker and Introduction to Docker, In this post we’re going to understand use of Docker Volumes and Bind Mounts.
As per official document, By default all files created inside a container are stored on a writable container layer. This means that:
- The data doesn’t persist when that container no longer exists, and it can be difficult to get the data out of the container if another process needs it.
- A container’s writable layer is tightly coupled to the host machine where the container is running. You can’t easily move the data somewhere else.
- Writing into a container’s writable layer requires a storage driver to manage the filesystem. The storage driver provides a union filesystem, using the Linux kernel. This extra abstraction reduces performance as compared to using data volumes, which write directly to the host filesystem.
Docker has two options for containers to store files in the host machine, so that the files are persisted even after the container stops: volumes, and bind mounts.
In short, By default all files created inside a container are stored on a writable container layer i.e, The data doesn’t persist when that container no longer exists, and it can be difficult to get the data out of the container if another process needs it.
Docker has 3 options for containers to store files in the host machine, so that the files are persisted even after the container stops:
- Anonymous volumes
- Named volumes
- Host volume or Bind volumes
Anonymous Volumes
Let’s create a container with an anonymous volume which is mounted as /data
on container. In this case we mention container directory name “data”. On host system it will map to a random-hash directory under /var/lib/docker/volumes/ directory.
docker run -it --name mycontainer -v /data nginx /bin/bash
On Host to verify volume
docker volume ls docker inspect <volume_name>
Named Volumes
Create a container with a named volume name which is mounted as /data1
on container.
docker volume create myvol docker volume ls docker volume inspect myvol
docker run -it --name mycontainer2 -v myvol:/data1 nginx /bin/bash
Bind Mounts
In this we will map host directory, create a host volume
mkdir /opt/tempdata docker run -it --name vtwebuat03 -v /opt/tempdata:/data02 nginx /bin/bash