Bind mount docker windows

Introduction

Docker volumes are essential for managing data persistence and sharing it between host systems and containers. Windows users often encounter various approaches to achieving this. In this blog post, we will explore four distinct methods for mounting volumes in Windows using Docker.

Method 1: Using -v Flag with Absolute Path

The -v flag is commonly used to specify volume mounts in Docker. When working in Windows, it’s crucial to employ an absolute path to the directory you wish to mount.

docker run --rm -it -v /$(pwd):/data busybox bin/sh

Explanation:

  • --rm: Removes the container after it exits.
  • -it: Runs the container interactively.
  • -v /$(pwd):/data: Mounts the current working directory on the host to /data in the container. Note the use of / before $(pwd).

Method 2: Using --mount Flag with bind Type

The --mount flag provides greater flexibility in specifying volume mounts. With the bind type, you can bind a specific directory on your host to a directory in the container.

docker run --rm -it --mount type=bind,src=C:/temp/docker,target=/data busybox bin/sh

Explanation:

  • --mount type=bind,src=C:/temp/docker,target=/data: Binds the C:/temp/docker directory on the host to /data in the container.

Method 3: Using UNC Path for Windows Shares

In this method, you can utilize a UNC (Universal Naming Convention) path to mount a directory from a Windows network share.

docker run --rm -it -v //server/share:/data:ro busybox bin/sh

Explanation:

  • -v //server/share:/data:ro: Mounts the \\server\share network share on the host to /data in the container with read-only permissions (ro).

Method 4: Using --mount Flag with a Named Volume

Named volumes are an effective way to manage persistent data in Docker. You can create a named volume and mount it to a container.

docker volume create codeguru
docker run -it --mount source=codeguru,target=//data busybox sh

Explanation:

  • docker volume create codeguru: Creates a named volume named codeguru.
  • --mount source=codeguru,target=//data: Mounts the codeguru volume to /data in the container.

Conclusion

In this blog post, we’ve explored four different methods for mounting volumes in Windows using Docker. Each approach offers unique advantages and suits various use cases. By understanding these techniques, you’ll be better equipped to manage data persistence in your Docker containers on Windows.

Одна из самых часто обсуждаемых вопросов у пользователей Docker Desktop — обмен файлами между системами (file sharing). Как посмотреть исходный код внутри моего контейнера? В чем различие между томом (volume) и привязкой монтирования (bind mount)? Почему file sharing работает медленнее, чем на Linux, и как это ускорить?

Примечание: здесь приведен перевод статьи [1].

[Bind mount и volume]

Предположим, что вы запустили контейнер Ubuntu командой docker run -it ubuntu bash. Вы наверняка быстро обнаружили, что: (1) у контейнера своя собственная файловая система, основанная на файловой системе в образе Ubuntu; (2) вы можете создавать, удалять и изменять файлы, но все эти изменения остаются локальными для контейнера и теряются, когда контейнер удален; (3) у контейнера нет доступа к каким-либо файлам на вашем компьютере хоста (наример на ноутбуке, где установлен docker, под которым запущена в docker операционная система Ubuntu).

Из-за этого встают вполне естественные вопросы: как увидеть в контейнере другие файлы? Как контейнеру записать куда-нибудь данные, которые можно прочитать позже, или возможно использовать в других контейнерах? Это как раз то, где вступают в действие такие сущности, как bind mount и volume. Обе эти возможности используют флаг -v команды docker run, чтобы указать некоторые файлы для совместного использования с контейнером.

Bind mount. Первая опция, которую многие используют, это bind mount, где часть от вашей файловой системы становится общей с контейнером. Например:

docker run -it -v /users/stephen:/my_files ubuntu bash

В этом примере файлы в /users/stephen будут доступны в каталоге /my_files контейнера, и вы можете обращаться к ним на чтение и запись. Это очень просто и удобно но если вы используете Docker Desktop и именованный том (named volume), то можете получить лучшую производительность.

Named volume. Вторая опция это именованный том (named volume), это файловая система, управляемая Docker. Вы можете создать named volume командой наподобие docker volume create new_vol, и затем сделать этот том общим, снова используя флаг -v, например:

docker run -it -v new_vol:/my_files ubuntu bash

Созданные таким способом тома останутся, даже когда контейнер удален, и они могут быть сделаны общими для других контейнеров. Вы также можете просматривать содержимое этих томов из оболочки Docker Desktop, используя закладку Volumes.

[Вопросы производительности]

Чтобы понимать отличие параметров производительности между двумя этими опциями, давайте сначала кратко поговорим о том, как работает Docker Desktop. Многие представляют себе, что Docker Desktop — это просто пользовательский интерфейс поверх некоторых инструментов с открытым исходным кодом, но это лишь малая часть того, что есть на самом деле. Docker Desktop это среда разработки и запуска Linux-контейнеров на хосте, т. е. на вашей машине с операционной системой Mac или Windows, с бесшовной интеграцией с хостом таким образом, чтобы гостевые опеционные системы (т. е. те, что работаю в контейнерах) работали естественным для себя образом. Docker Desktop делает это, настраивая Linux VM (виртуальную пашину Linux, или опционально окружение WSL 2 на Windows [2]), в которой можно запустить движок Docker и контейнеры, и затем передавать данные CLI-команд, сети и файлов между хостом и VM.

К сожалению, из-за внутренней организации подсистемы виртуализации всегда существуют неизбежные небольшие накладные расходы при пересечении границы между хостом и виртуальной машиной. Эти расходы невелики, но в системе разработки, где имеется большое дерево исходного кода, когда происходит множество операций чтения и записи (что часто имеет место при кросс-компиляции Linux для встраиваемых систем), эти расходы складываются, что может заметно влиять на производительность. И поскольку Docker Desktop хорош в том, чтобы скрыть лежащую в его основе виртуальную машину (VM), для его пользователей не всегда очевидно, почему падает производительность его контейнеров. На Linux у контейнера есть прямой доступ к bind-mounted файловой системе, а поскольку реализация Docker Desktop на Mac и Windows работает для пользователей прозрачно, то пользователи интуитивно ожидают получить такую же производительность, как на Docker в среде Linux.

Именованные тома (named volumes) не страдают от той же проблемы, потому что они создаются внутри собственной файловой системы VM, так что они работают так же быстро, как и на машине Linux. На WSL 2 операционная система Windows управляет общими файлами (file sharing) вместо управления Docker, но вступают в действие те же вопросы производительности: файлы, смонтированные из файловой системы Windows, могут быть медленными, именованные тома быстрыми, но в этом случае есть другой вариант: файлы, сохраненные в файловой системе Linux, также находятся внутри WSL VM, поэтому они также работают быстро.

[Практические советы]

Описанные выше соображения дают нам понимание, что следует сделать в плане оптимизации производительности. Сначала попробуйте bind mount, это довольно удобно, и возможно вполне будет соответствовать вашим требованиям. Но если производительность становится проблемой, то проверьте:

(1) Вы действительно сделали общими только то, что действительно необходимо, и не более.
(2) Подумайте, как оганизовать обмен файлами каким-то другим способом, без bind mount.

У вас есть несколько вариантов хранить файлы внутри VM, включая named volume, файлы Linux в WSL, и в файловой системе контейнера: какой из вариантов использовать, зависит от конкретной ситуации. Например:

• Исходный код, который вы активно редактируете на машине хоста, вероятно лучше всего расшарить через bind mount.
• Большие, статические деревья зависимостей или библиотеки можно переместить в именованный том (named volume), или WSL, или даже записать в образ контейнера.
• Базы данных болше подходят для хранения в named volume или WSL.
• Директории кэша и больших файлов должны быть помещены в named volume или WSL (если вам нужно сохранить их после остановки контейнера), или должны находиться в файловой системе контейнера (если они могут исчезать вместе с контейнером).
• Файлы, которые не нужны контейнеру, вообще не должны быть общими. В частности, не расшаривайте всю домашнюю директорию. Часто пользователи неразумно поступают подобным образом, чтобы у них был доступ к любым файлам, но в отличие от docker Linux это не «бесплатно».

Остается вариант, когда реально нужно применить bind mount для большой директории или для большго трафика — сторонние решения кэширования/синхронизации, например Mutagen или docker-sync. Они фактически копируют ваши файлы внутри VM для ускорения доступа на чтение/запись, и обрабатывают синхронизацию (в одном или обоих направлениях) между копией и хостом. Но это предполагает внедрение дополнительного компонента для управления, так что named volume по-прежнему предпочтительно использовать везде, где это возможно.

[Дополнительные замечания]

На протяжении многих лет мы использовали различные реализации совместного использования файлов между системами (Samba и gRPC FUSE на Windows Hyper-V; osxfs и gRPC FUSE на Mac; Windows с использованием 9P на WSL 2). Со временем мы добились некоторых улучшений в плане производительности, но ни одно из них не может достичь собственной производительности системы (native performance). Есть некоторые надежды на новую перспективную реализацию файлообмена на основе virtiofs. Это новая технология, специально разработанная для шаринга файлов между хостом и VM. Она способна существенно повысить производительность, потому что используется тот факт, что VM и хост работают на одной машине, а не в сети.

Мы уже выпустили превью технологии virtiofs для Docker Desktop for Mac, которую вы можете получить из нашей public roadmap [3] (это требует 12.2), и также планируется использовать это для разрабатываемого Docker Desktop for Linux. Вероятно эта технология также сделает несколько быстрее работу bind mount (хотя все еще рекомендуется использовать named volume или собственную файловоую систему контейнера для подходящих случаев).

Если вы намерены глубже ознакомиться с этими темами, то есть смысл обратиться к материалам публикации Jacob Howard, см. [4]. Это масса информации и практических советов, поместившихся в видеоролик из 26 минут.

[Ссылки]

1. File Sharing with Docker Desktop site:docker.com.
2. Запуск Linux на Windows помощью WSL.
3. [Docker Desktop] Improve Mac File system performance site:github.com.
4. A Pragmatic Tour of Docker Filesystems site:xenoscopic.com.
5. Шаринг локальных фалов хоста для контейнеров.

The short answer

To mount a local directory into a Docker container (i.e. bind mount), you can use the docker run command combined with the -v option flag (short for —volume) as follows:

$ docker run -v <host_directory>:<container_directory> <image>

Where:

  • host_directory is the absolute or relative path of the bind mount on your local machine.
  • container_directory is the absolute path of the file or directory within the container.
  • image is the name of the Docker image the container will be launched from.

For example:

$ docker run -v ./app:/app node-server

The above command mounts the app directory in the current directory into the container at the /app path using the -v flag.

Note that if the specified directory doesn’t exist on your local machine, Docker will automatically create it before starting the container.

Also note that the use of relative local paths are only available as of Docker version 23.

If instead you are looking for persistent storage, you can read more about named volumes on the official Docker volumes page.

Easily retrieve this command using Warp’s AI Command Search

If you’re using Warp as your terminal, you can easily retrieve this command using the Warp AI Command Search feature:

Entering docker run volume directory in the AI Command Search will prompt an docker run command that can then quickly be inserted into your shell by doing CMD+ENTER.

The —volume and —mount flags

The —volume and —mount flags are both used to mount a file or a directory into a container and essentially have the same behavior, only with a different syntax.

The —volume flag

The -v (or —volume) flag consists of three fields, separated by colon characters:

$ docker run -v <source>:<destination>:<options> <image>

Where:

  • The source field is the path of the file or directory on the host machine.
  • The destination field is the path where the file or directory is mounted into the container.
  • The options field is a comma separated list of options.

For example:

$ docker run -v ./app:/app:ro alpine

The —mount flag

The —mount flag consists of multiple key-value pairs, separated by commas and each consisting of a key=value tuple:

$ docker run --mount type=<type>,source=<source>,destination=destination>,<options> <image>

Where:

  • The type field is the type of the mount, which should be set to bind when using bind mounts.
  • The source field is the path of the file or directory on the host machine.
  • The destination field is the path where the file or directory is mounted into the container.
  • The options field is a comma separated list of options.

For example:

$ docker run -v --mount type=bind,source=./app,destination=/app alpine,readonly

Differences between —volume and —mount

Besides their syntax, the only difference between these flags is their behavior when it comes to creating bind-mounted directories that don’t exist.

When using the -v or —volume flag, Docker will automatically create the bind-mounted directory on your local machine if it doesn’t exist.

When using the —mount flag, Docker will not create the bind-mounted directory on your local machine if it doesn’t exist and generate an error.

You can learn more about bind mounts on the official Docker documentation page.

Mounting files and directories into a container

As of Docker version 23, you can mount a local file or directory into a container using either its relative or absolute path.

Mounting the current directory

To mount the current directory into the container at a specified path, you can use the dot syntax as follows:

$ docker run -v .:/path/to/directory <image>

To mount the current directory at the same path into the container, you can use the command substitution syntax with the pwd command as follows:

$ docker run -v $(pwd):$(pwd) <image>

Note that when using this syntax, Docker will automatically create all the intermediary directories starting from the root in order to preserve the directory structure.

Mounting a file

To mount a single file into a container, you can use the same syntax as for directories:

$ docker run -v /path/to/file:/path/to/file <image>

Using multiple bind mounts

To mount several files or directories into a container, you can repeat the -v flag multiple times as follows:

$ docker run -v ./dir_1:/app/dir_1 -v ./dir_2:/app/dir_2 <image>

Use a read-only bind mounts

By default, any modifications made by a container to the files and directories of a bind mount will be propagated back to the local machine.

To prevent that, you can define a bind mount as read-only, either using the ro option when working with the -v flag:

$ docker run -v ./app:/app:ro alpine

Or the readonly option when working with the —mount flag:

$ docker run --mount type=bind,source=./app,target=/app,readonly alpine

Using bind mounts on Windows

When working with Docker for Windows, there are essentially two ways you can write the paths of the files and directories you want to mount into a container.

You can either use escaped Windows-like paths as follows:

$ docker run -v C:\\Users\\user\\work:/work <image>

Or you can use Unix-like paths as follows:

$ docker run -v //c/Users/user/work:/work <image>

Note that when using the $(pwd) command substitution, you will have to prepend a slash character to this expression in order for it to work:

$ docker run -v /$(pwd):/work <image>

When building containerized applications with Docker, one common frustration developers face is the lack of live updates when editing code. For example, you tweak server.js or a front-end file, but the changes don’t reflect in the running app. Why?

Because Docker copies your project files into the container when you build the image. Once the container starts, it runs on that static snapshot—isolated from your host file system.

Restarting the container every time you make a change? That’s inefficient.

Enter: Bind Mounts.


What Are Bind Mounts?

Bind mounts allow you to map a file or directory on your host machine to a path inside your running container.

This means:

  • Your container reads real-time code from your host.
  • You can make live changes on your local system, and see them reflected instantly inside your container.

Unlike volumes, which are fully managed by Docker, bind mounts give you control over where and what to mount.


Practice Resource

How Bind Mounts Work

Let’s walk through a typical development scenario using a Node.js app:

Step 1: Build the Docker Image

docker build -t feedback-node-app:volumes .

Enter fullscreen mode

Exit fullscreen mode

bind-mount-project

This creates the Docker image from your Dockerfile. But the actual code editing experience depends on how you run the container.


Step 2: Run with Bind Mounts

docker run -p 3000:80 --name feedback-app --rm -d \
  -v feedback:/app/feedback \
  -v "/Users/mayankgupta/dev/project-folder:/app" \
  feedback-node-app:volumes

Enter fullscreen mode

Exit fullscreen mode

Now your project folder is bound to /app inside the container. Any changes made locally update live in the container.


Common Pitfall: Container Crashes

You might notice the container auto shuts down after running the above command.

Why? Because when you mount your local folder (/app), it overwrites the container’s internal /app, including installed node_modules. Poof—dependencies gone.


Fix: Use Anonymous Volumes

Mount node_modules from inside the container to preserve its contents:

docker run -p 3000:80 --name feedback-app --rm -d \
  -v feedback:/app/feedback \
  -v "/Users/mayankgupta/dev/project-folder:/app" \
  -v /app/node_modules \
  feedback-node-app:volumes

Enter fullscreen mode

Exit fullscreen mode

Now you get live updates without breaking dependencies.


Why Anonymous Volumes Help

When you mount your local project folder, it replaces everything in /app—including node_modules. Mounting /app/node_modules separately tells Docker:

“Use an isolated volume just for node_modules, don’t replace it with the host.”

This protects your container-specific files while still giving you live bind mounts for code.


Instant Feedback with Live Changes

Try adding a line like:

console.log("TEST");

Enter fullscreen mode

Exit fullscreen mode

in server.js. Boom—you’ll see the output instantly without rebuilding the image. That’s the magic of bind mounts.


Development Shortcuts

Typing full paths is tedious. Here’s a shortcut:

  • macOS / Linux:
  -v $(pwd):/app

Enter fullscreen mode

Exit fullscreen mode

  • Windows:
  -v "%cd%":/app

Enter fullscreen mode

Exit fullscreen mode

This mounts your current directory to /app.


Securing Your Code: Read-Only Mounts

Sometimes, you want the container to read but not write to your host files. Easy fix: add :ro to the mount path.

-v "/host/path:/app:ro"

Enter fullscreen mode

Exit fullscreen mode

Useful when mounting application code you don’t want Docker to modify.

But for folders like temp/, which need write access, you can still mount them as container-only volumes:

-v app/temp

Enter fullscreen mode

Exit fullscreen mode


Full Run Command Example

docker run -p 3000:80 -d --name feedback-app \
  -v feedback:/app/feedback \
  -v "/Users/mayankgupta/dev/project-folder:/app:ro" \
  -v /app/node_modules \
  -v /app/temp \
  feedback-node-app:volumes

Enter fullscreen mode

Exit fullscreen mode

This setup gives:

  • Persistent feedback data via named volume
  • Live code updates via bind mount
  • Safe dependencies and temp file handling via anonymous volumes

Docker Volume Management

Docker-managed volumes give you additional control:

Command Description
docker volume ls List all Docker volumes
docker volume create <name> Create a volume
docker volume rm <name> Remove a volume
docker volume prune Delete all unused volumes
docker volume inspect <name> Inspect volume metadata

Bind mounts won’t appear with ls command—they’re not managed by Docker.


COPY vs Bind Mount

COPY is used in the Dockerfile to snapshot your app at image build time.

Bind Mount is runtime behavior—great for development, not production.

Should we still use COPY even when bind mounting?

Yes. During production, bind mounts are NOT used. COPY ensures your image includes everything needed to run independently of your dev environment.


.dockerignore: Keep Your Image Clean

Just like .gitignore, use .dockerignore to prevent copying unnecessary files into the Docker image:

node_modules
Dockerfile
.git
.env

Enter fullscreen mode

Exit fullscreen mode

This:

  • Reduces image size
  • Improves build speed
  • Avoids leaking secrets or local clutter

Conclusion

Bind mounts are an essential part of the modern Docker development workflow. They allow you to:

  • See changes instantly
  • Separate dev vs production workflows
  • Keep code and data organized across environments
    ****
    Used wisely, bind mounts can save countless hours of rebuilding and restarting—making your dev experience smoother and more productive.

References

  • Docker Docs: Bind Mounts
  • Docker Volumes vs Bind Mounts

Bind mounts and the host filesystem are tightly related. The host filesystem is immediately impacted by changes made to a bind mount, and vice versa. When you use a bind mount to remove a container, the related data stays on the host.

What is Docker Volume?

Applications can be run independently using Docker containers. By default, when a container is deleted or recreated, all of the modifications (data) within it are lost. Docker volumes and bind mounts can be useful if we wish to save data in between runs. In order to protect data created by the running container, Docker volumes are file systems mounted on Docker containers.

What is Bind Mount in Docker?

Bind mounts may be stored anywhere on the host system. They may even be important system files or directories. Non-Docker processes on the Docker host or a Docker container can be modified at any time. You can create a file on the host system and attach it to the container where you want to maintain the state of the Docker. You can also use the bind mount for stateful applications.

What is the Docker Volume Driver Plugin?

The Docker Volume Driver Plugin is a tool that extends Docker’s functionality by allowing users to use different storage backends for managing volumes in Docker containers.

Here’s a simple breakdown:

  1. Volumes in Docker: Volumes are used in Docker to store and manage data that needs to persist beyond the lifecycle of a container.
  2. Driver Plugin: The Volume Driver Plugin expands Docker’s capabilities by enabling users to use various storage systems (like cloud storage, network storage, or specialized storage solutions) as the backend for managing Docker volumes.
  3. Flexibility: By using Volume Driver Plugins, Docker users can choose the most suitable storage solution for their specific needs, such as performance requirements, scalability, or integration with existing infrastructure.
  4. Customization: These plugins allow Docker to integrate with external storage platforms seamlessly, making it easier to manage and scale containerized applications while maintaining data integrity and availability.

Types of Docker Volume Driver Plugins are Available

In docker we mainly use two docker driver volume plugins, They are.

1. Local Driver (Steps To Create Custom Docker Volume Using Local Driver)

The Local Driver is a built-in Docker volume plugin that allows users to create volumes using local storage on the host machine. Follow the steps below to use the local driver to create the volume using a local driver.

Steps to Create Custom Volume:

  1. Use the command docker volume create -d local <Name_Of_the_Volume> to create a Docker volume using the Local Driver.
  2. Replace <Name_Of_the_Volume> with the desired name for the volume.

Docker Volume Create

docker create volume -d local <Name Of the Volume>

Usage Example: Creating a volume named «GFG-Volume» using the Local Driver: docker volume create -d local GFG-Volume.

2. REX-RAY Driver

To learn more about the docker rex-ray plugin please refer to the the following article.

  • Description: REX-Ray is an external Docker volume plugin that provides support for various storage solutions, including cloud storage and networked storage.
  • Usage: REX-Ray needs to be installed separately and configured to integrate with Docker.
  • Benefits: REX-Ray simplifies the management of volumes by allowing Docker to interact with external storage systems seamlessly.
  • Usage Example: Once REX-Ray is installed and configured, Docker users can utilize its capabilities to create and manage volumes across different storage platforms.

What Is Docker REX – RAY Plugin ?

How to List the Docker Volumes?

The docker volume ls command is used to list all the volumes created on the Docker host. It provides detailed information about each volume, including its name, driver, and optionally other properties such as mount point. You can list all the docker volumes that are available in the docker by using a simple command as shown below.

docker volume ls

«docker volume ls» will list all the docker volumes which are available in the docker host and also it will list the volume which are managed out side of the docker host as shown in the image below.

docker volume ls

Steps to Create And Attach Bind Mount To The Docker Container

Follow the steps Mentioned below to create and attach the bind mount to docker container.

Step 1: Create an Empty Directory on the Docker Host

This command creates an empty directory on the Docker host. This directory will act as a volume that can be mounted to the container.

Mkdir <Name Of the Volume You wan to Create>

Step 2: Attach the Bind Mount to the Docker Container

Know this directory will act as an volume on the docker host you need to mount this to the path where the data will be stored in the application as show in the image below you can use the following command to do this.

 sudo docker run -d <Container ID> --name <Name Of the Container> -v <Host Path>:<Container Path>
  • <Container_ID>: The ID of the container to which you want to attach the bind mount.
  • <Name_Of_the_Container>: The name you want to give to the container.
  • <Host_Path>: The path of the directory on the Docker host that you created in step 1.
  • <Container_Path>: The path inside the container where you want to mount the volume.

All the steps

/home/ubuntu/nginx is the host path where my directory of volume is located and the /app is the container path.

Choose the -v or —mount flag

When working with Docker, choosing between the -v and --mount flag depends on your specific needs and the complexity of your volume requirements.

Here’s a simple breakdown to help you choose:

  • -v Flag:
    • This is the shorthand notation for specifying volumes.
    • It’s easier to use and more commonly used for basic volume mounting tasks.
    • It’s suitable for simple volume setups, such as mounting a single directory from the host into a container.
docker run -v /host/directory:/container/directory ...
  • --mount Flag:
    • Provides more flexibility and options for defining volumes.
    • It allows you to specify additional options like read-only, consistency, and volume driver.
    • Suitable for advanced volume configurations and scenarios where finer control over volume properties is needed.
docker run --mount type=bind,source=/host/directory,target=/container/directory ...

This is particularly useful when you need to define more complex volume configurations or when using volume plugins like NFS or REX-Ray.

Differences between -v and —mount behavior

Aspect -v Flag (Shorthand) —mount Flag (Advanced)
Ease of Use Simple to use with shorter syntax. Requires specifying volume type and additional options, which can be more complex.
Flexibility Limited flexibility, primarily for basic volume mounting. Offers greater flexibility and control over volume properties and options.
Additional Options Limited options for additional configuration (e.g., read-only). Provides additional options like specifying volume driver, read-only mode, and more.

Where are Docker bind mounts stored?

Docker bind mounts are stored on the host machine where Docker is running. When you create a bind mount, you specify a path on the host machine that you want to share with the container. Docker then links this path to a location inside the container.

Docker bind mounts are stored in directories on your computer’s file system, and these directories are accessible both inside the Docker container and from outside, allowing easy sharing of files and data between the container and the host machine.

How to mount a host directory in a Docker container

To mount a host directory in a Docker container using a Docker Compose file, you can specify the volumes configuration within the services section. Here’s a simple example:

version: '3.8'

services:
my_container:
image: my_image:latest
volumes:
- /path/on/host:/path/in/container

  • my_container: This is the name of your container service.
  • image: Specifies the Docker image to use for the container.
  • volumes: Defines the volumes to mount into the container.
    • /path/on/host: This is the path to the directory on the host machine that you want to mount.
    • /path/in/container: This is the path inside the container where you want to mount the directory.

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Ошибка 80240016 центра обновления windows 7
  • How to uninstall postgresql windows
  • Canon lbp 29008 драйвер windows 10
  • Cyberarms security software intrusion detection for windows
  • Windows xp поддержка full hd