Mapping Host Directories to Container Volumes

One of the important features of Docker is the ability to map host directories to container volumes. This allows us to share files and directories between the host machine and the Docker container. It provides a convenient way to persist data and make it accessible from both the host and the container.

Understanding Host Directories and Container Volumes

In Docker, a container is an isolated environment that runs a specific application. It has its own file system that is separate from the host machine. However, we can map directories from the host machine to the container's file system by using the -v or --volume flag when running a container.

A host directory refers to a directory on the host machine that we want to share with the container. On the other hand, a container volume is a directory inside the container's file system where the contents of the host directory will be mounted.

Mapping Directories with the docker run Command

To map a host directory to a container volume, we can use the following syntax with the docker run command:

docker run -v <host directory>:<container volume> <image>

For example, let's say we have a directory called data on our host machine, and we want to map it to a container volume called /data:

docker run -v /path/to/host/data:/data <image>

Now, any files or directories inside /path/to/host/data will be accessible from within the container at /data.

Mounting Read-Only Volumes

By default, the volumes created by Docker are writable by both the host and the container. However, there might be cases where we want to make a volume read-only inside the container. To do this, we can use the :ro suffix after the container volume:

docker run -v /path/to/host/data:/data:ro <image>

With this configuration, any modifications made to /data inside the container will not be persisted on the host machine.

Mapping Specific Subdirectories

Sometimes, we might not want to map the entire directory from the host machine to the container. Instead, we may only want to map specific subdirectories. We can achieve this by specifying the subdirectory path after the host directory:

docker run -v /path/to/host/data/subdir:/data <image>

Now, only the contents of subdir inside the host's data directory will be accessible at /data in the container.


Mapping host directories to container volumes is a powerful feature of Docker that allows us to easily share and persist data between the host machine and containers. It provides flexibility and convenience when working with Dockerized applications. By understanding the concept and using the docker run command with the correct syntax, we can seamlessly integrate host directories into Docker containers.

© NoobToMaster - A 10xcoder company