Mounting a Host Directory as a Volume
Mounting a host directory as a volume in a Docker container is a common use case, as it allows you to share data between the host and the container, and to persist data beyond the lifetime of the container.
To mount a host directory as a volume, you can use the -v
or --mount
flag when running a Docker container. Here's an example using the -v
flag:
docker run -v /host/path:/container/path image:tag
In this example, /host/path
is the path on the host file system that you want to mount, and /container/path
is the path within the container where the volume will be mounted.
You can also use the --mount
flag to mount a host directory as a volume:
docker run --mount type=bind,source=/host/path,target=/container/path image:tag
The type=bind
option specifies that we are mounting a host directory as a volume, and the source
and target
options specify the host and container paths, respectively.
It's important to note that the host directory must already exist before you can mount it as a volume. If the directory does not exist, Docker will create it for you.
Here's an example of how you might use a mounted host directory in a Docker container:
## Create a directory on the host
mkdir /host/data
## Run a container and mount the host directory as a volume
docker run -v /host/data:/app/data image:tag
In this example, we create a directory /host/data
on the host, and then mount it as a volume at the /app/data
path within the container. Any data written to /app/data
within the container will be persisted on the host file system.
Overall, mounting a host directory as a volume in a Docker container is a powerful way to share and persist data between the host and the container.