0
0
DockerHow-ToBeginner · 3 min read

How to Use Bind Mount in Docker: Syntax and Examples

Use a bind mount in Docker by adding the -v or --mount flag with the host path and container path separated by a colon, like -v /host/path:/container/path. This lets your container access files directly from your host machine.
📐

Syntax

The basic syntax for a bind mount in Docker uses the -v or --mount option to link a directory or file from your host to the container.

  • -v /host/path:/container/path: Mounts the host directory or file at /host/path into the container at /container/path.
  • --mount type=bind,source=/host/path,target=/container/path: A more explicit syntax introduced in Docker 17.06+ that clearly defines the mount type and paths.

Both methods let the container read and write files directly on your host system.

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

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

Example

This example shows how to run an nginx container that serves a static website from a folder on your host machine.

We mount the host folder /home/user/website to the container's /usr/share/nginx/html directory where nginx serves files.

bash
docker run -d -p 8080:80 -v /home/user/website:/usr/share/nginx/html:ro nginx
Output
a1b2c3d4e5f6g7h8i9j0 # Container runs in background, serving files from host folder on http://localhost:8080
⚠️

Common Pitfalls

  • Wrong host path: The host path must exist; otherwise, Docker creates an empty directory which may cause confusion.
  • Permission issues: The container user must have permission to read/write the host files.
  • Read-only mounts: Add :ro at the end of the volume to prevent container from modifying host files.
  • Using relative paths: Always use absolute paths for host directories.
bash
docker run -v ./website:/usr/share/nginx/html nginx
# This creates an empty directory inside the container if ./website does not exist or is relative.

docker run -v /home/user/website:/usr/share/nginx/html:ro nginx
# Mounts the folder read-only to protect host files.
📊

Quick Reference

OptionDescriptionExample
-v /host/path:/container/pathBind mount host directory to containerdocker run -v /data:/app/data myimage
--mount type=bind,source=/host/path,target=/container/pathExplicit bind mount syntaxdocker run --mount type=bind,source=/data,target=/app/data myimage
:roMake mount read-onlydocker run -v /data:/app/data:ro myimage
Absolute pathsHost paths must be absoluteUse /home/user/data, not ./data

Key Takeaways

Use -v or --mount with absolute host paths to create bind mounts in Docker.
Bind mounts let containers access and modify files directly on your host machine.
Add :ro to make mounts read-only and protect host files.
Ensure host paths exist and permissions allow container access.
Prefer --mount syntax for clarity and newer Docker versions.