How to Mount a Host Directory in a Docker Container

One of Docker’s most powerful features is the ability to mount a directory from your host machine into a container. This allows you to:

  • Share code or configuration files between host and container
  • Persist container data on the host
  • Live-edit files during development

In this blog, you’ll learn how to mount a host directory in a Docker container using the -v or --mount flag, when to use each, and common pitfalls to avoid.


🧠 Why Mount a Directory?

Mounting host directories into containers lets you:

  • Avoid rebuilding images for every file change
  • Access logs or output files generated by containers
  • Use local configuration files (e.g., .env, .yaml) directly
  • Store persistent data like databases outside the container

✅ Syntax 1: Use -v (Volume Mount)

docker run -v /path/on/host:/path/in/container my-image

Example:

docker run -v $(pwd)/app:/usr/src/app node:18
  • The code from your current directory (./app) will be mounted to /usr/src/app in the container.
  • Changes in either location are reflected immediately.

✅ Syntax 2: Use --mount (More Explicit)

docker run \
  --mount type=bind,source=/path/on/host,target=/path/in/container \
  my-image

Example:

docker run \
  --mount type=bind,source="$(pwd)/data",target=/app/data \
  python:3.11

The --mount syntax is more verbose but easier to read and manage in complex scripts or Compose files.


📌 Difference Between -v and --mount

Feature-v or --volume--mount
Simpler syntax
Better readability
Recommended forQuick CLI usageScripts & production setup

🛠️ Use with Docker Compose

In docker-compose.yml, you can define volume mounts like this:

services:
  web:
    image: nginx
    volumes:
      - ./html:/usr/share/nginx/html

This will mount the local html directory into the container’s web root.


⚠️ Permissions & Path Tips

  • Make sure the host directory exists. Docker won’t auto-create nested folders.
  • On Windows or macOS, paths must be absolute or properly escaped.
  • Some base images may need chown or chmod to access mounted directories.

📝 Conclusion

Mounting a host directory into a Docker container is a must-know technique for development, debugging, and data persistence. Whether you use -v or --mount, this simple feature can dramatically improve your container workflows.


🔑 Quick Summary

TaskCommand Example
Mount with -vdocker run -v /host:/container my-image
Mount with --mountdocker run --mount type=bind,source=/h,target=/c
In Docker Composevolumes: - ./local:/container/path
Sharing Is Caring:

Leave a Comment