0
0
DockerHow-ToBeginner · 3 min read

How to Mount Host Directory in Docker: Simple Guide

To mount a host directory in Docker, use the -v or --mount option with docker run. For example, docker run -v /host/path:/container/path image mounts the host directory /host/path into the container at /container/path.
📐

Syntax

The basic syntax to mount a host directory into a Docker container uses either -v or --mount options:

  • -v or --volume: -v /host/path:/container/path[:options]
  • --mount: --mount type=bind,source=/host/path,target=/container/path[,options]

Here, /host/path is the directory on your computer, and /container/path is where it will appear inside the container.

bash
docker run -v /host/path:/container/path image

docker run --mount type=bind,source=/host/path,target=/container/path image
💻

Example

This example runs an alpine container and mounts the host directory /tmp/data to /data inside the container. It then lists the contents of /data inside the container.

bash
docker run --rm -v /tmp/data:/data alpine ls /data
Output
file1.txt file2.txt
⚠️

Common Pitfalls

Common mistakes when mounting host directories include:

  • Using relative paths instead of absolute paths on the host.
  • Mounting a file instead of a directory.
  • Not having proper permissions on the host directory, causing access errors.
  • Confusing -v and --mount syntax.

Always use absolute paths and check permissions before running the container.

bash
docker run -v data:/data alpine ls /data  # Wrong: 'data' is relative path

docker run -v /absolute/path/data:/data alpine ls /data  # Correct: absolute path
📊

Quick Reference

Use this quick reference to remember the options:

OptionDescriptionExample
-v or --volumeMount host directory or file-v /host/path:/container/path
--mountMore explicit and flexible mount syntax--mount type=bind,source=/host/path,target=/container/path
roMount read-only (optional)-v /host/path:/container/path:ro
rwMount read-write (default)-v /host/path:/container/path:rw

Key Takeaways

Always use absolute host paths when mounting directories in Docker.
Use -v for simple mounts and --mount for more explicit control.
Check host directory permissions to avoid access errors inside containers.
Mounts allow containers to read/write files on your host system.
Use :ro option to mount directories as read-only for safety.