Linux mount bind directory

Use bind mounts

Estimated reading time: 13 minutes

Bind mounts have been around since the early days of Docker. Bind mounts have limited functionality compared to volumes. When you use a bind mount, a file or directory on the host machine is mounted into a container. The file or directory is referenced by its absolute path on the host machine. By contrast, when you use a volume, a new directory is created within Docker’s storage directory on the host machine, and Docker manages that directory’s contents.

The file or directory does not need to exist on the Docker host already. It is created on demand if it does not yet exist. Bind mounts are very performant, but they rely on the host machine’s filesystem having a specific directory structure available. If you are developing new Docker applications, consider using named volumes instead. You can’t use Docker CLI commands to directly manage bind mounts.

Choose the -v or —mount flag

In general, —mount is more explicit and verbose. The biggest difference is that the -v syntax combines all the options together in one field, while the —mount syntax separates them. Here is a comparison of the syntax for each flag.

Tip: New users should use the —mount syntax. Experienced users may be more familiar with the -v or —volume syntax, but are encouraged to use —mount , because research has shown it to be easier to use.

  • -v or —volume : Consists of three fields, separated by colon characters ( : ). The fields must be in the correct order, and the meaning of each field is not immediately obvious.
    • In the case of bind mounts, the first field is the path to the file or directory on the host machine.
    • The second field is the path where the file or directory is mounted in the container.
    • The third field is optional, and is a comma-separated list of options, such as ro , z , and Z . These options are discussed below.
  • —mount : Consists of multiple key-value pairs, separated by commas and each consisting of a = tuple. The —mount syntax is more verbose than -v or —volume , but the order of the keys is not significant, and the value of the flag is easier to understand.
    • The type of the mount, which can be bind , volume , or tmpfs . This topic discusses bind mounts, so the type is always bind .
    • The source of the mount. For bind mounts, this is the path to the file or directory on the Docker daemon host. May be specified as source or src .
    • The destination takes as its value the path where the file or directory is mounted in the container. May be specified as destination , dst , or target .
    • The readonly option, if present, causes the bind mount to be mounted into the container as read-only.
    • The bind-propagation option, if present, changes the bind propagation. May be one of rprivate , private , rshared , shared , rslave , slave .
    • The —mount flag does not support z or Z options for modifying selinux labels.

The examples below show both the —mount and -v syntax where possible, and —mount is presented first.

Differences between -v and —mount behavior

Because the -v and —volume flags have been a part of Docker for a long time, their behavior cannot be changed. This means that there is one behavior that is different between -v and —mount .

If you use -v or —volume to bind-mount a file or directory that does not yet exist on the Docker host, -v creates the endpoint for you. It is always created as a directory.

If you use —mount to bind-mount a file or directory that does not yet exist on the Docker host, Docker does not automatically create it for you, but generates an error.

Start a container with a bind mount

Consider a case where you have a directory source and that when you build the source code, the artifacts are saved into another directory, source/target/ . You want the artifacts to be available to the container at /app/ , and you want the container to get access to a new build each time you build the source on your development host. Use the following command to bind-mount the target/ directory into your container at /app/ . Run the command from within the source directory. The $(pwd) sub-command expands to the current working directory on Linux or macOS hosts. If you’re on Windows, see also Path conversions on Windows.

Читайте также:  Действия после установки windows

The —mount and -v examples below produce the same result. You can’t run them both unless you remove the devtest container after running the first one.

Use docker inspect devtest to verify that the bind mount was created correctly. Look for the Mounts section:

This shows that the mount is a bind mount, it shows the correct source and destination, it shows that the mount is read-write, and that the propagation is set to rprivate .

Stop the container:

Mount into a non-empty directory on the container

If you bind-mount into a non-empty directory on the container, the directory’s existing contents are obscured by the bind mount. This can be beneficial, such as when you want to test a new version of your application without building a new image. However, it can also be surprising and this behavior differs from that of docker volumes.

This example is contrived to be extreme, but replaces the contents of the container’s /usr/ directory with the /tmp/ directory on the host machine. In most cases, this would result in a non-functioning container.

The —mount and -v examples have the same end result.

The container is created but does not start. Remove it:

Use a read-only bind mount

For some development applications, the container needs to write into the bind mount, so changes are propagated back to the Docker host. At other times, the container only needs read access.

This example modifies the one above but mounts the directory as a read-only bind mount, by adding ro to the (empty by default) list of options, after the mount point within the container. Where multiple options are present, separate them by commas.

The —mount and -v examples have the same result.

Use docker inspect devtest to verify that the bind mount was created correctly. Look for the Mounts section:

Stop the container:

Configure bind propagation

Bind propagation defaults to rprivate for both bind mounts and volumes. It is only configurable for bind mounts, and only on Linux host machines. Bind propagation is an advanced topic and many users never need to configure it.

Bind propagation refers to whether or not mounts created within a given bind-mount or named volume can be propagated to replicas of that mount. Consider a mount point /mnt , which is also mounted on /tmp . The propagation settings control whether a mount on /tmp/a would also be available on /mnt/a . Each propagation setting has a recursive counterpoint. In the case of recursion, consider that /tmp/a is also mounted as /foo . The propagation settings control whether /mnt/a and/or /tmp/a would exist.

Propagation setting Description
shared Sub-mounts of the original mount are exposed to replica mounts, and sub-mounts of replica mounts are also propagated to the original mount.
slave similar to a shared mount, but only in one direction. If the original mount exposes a sub-mount, the replica mount can see it. However, if the replica mount exposes a sub-mount, the original mount cannot see it.
private The mount is private. Sub-mounts within it are not exposed to replica mounts, and sub-mounts of replica mounts are not exposed to the original mount.
rshared The same as shared, but the propagation also extends to and from mount points nested within any of the original or replica mount points.
rslave The same as slave, but the propagation also extends to and from mount points nested within any of the original or replica mount points.
rprivate The default. The same as private, meaning that no mount points anywhere within the original or replica mount points propagate in either direction.

Before you can set bind propagation on a mount point, the host filesystem needs to already support bind propagation.

For more information about bind propagation, see the Linux kernel documentation for shared subtree.

The following example mounts the target/ directory into the container twice, and the second mount sets both the ro option and the rslave bind propagation option.

The —mount and -v examples have the same result.

Now if you create /app/foo/ , /app2/foo/ also exists.

Configure the selinux label

If you use selinux you can add the z or Z options to modify the selinux label of the host file or directory being mounted into the container. This affects the file or directory on the host machine itself and can have consequences outside of the scope of Docker.

  • The z option indicates that the bind mount content is shared among multiple containers.
  • The Z option indicates that the bind mount content is private and unshared.

Use extreme caution with these options. Bind-mounting a system directory such as /home or /usr with the Z option renders your host machine inoperable and you may need to relabel the host machine files by hand.

Important: When using bind mounts with services, selinux labels ( :Z and :z ), as well as :ro are ignored. See moby/moby #32579 for details.

This example sets the z option to specify that multiple containers can share the bind mount’s contents:

It is not possible to modify the selinux label using the —mount flag.

Источник

Хранение данных в Docker

Важная характеристика Docker-контейнеров — эфемерность. В любой момент контейнер может рестартовать: завершиться и вновь запуститься из образа. При этом все накопленные в нём данные будут потеряны. Но как в таком случае запускать в Docker приложения, которые должны сохранять информацию о своём состоянии? Для этого есть несколько инструментов.

В этой статье рассмотрим docker volumes, bind mount и tmpfs, дадим советы по их использованию, проведём небольшую практику.

Особенности работы контейнеров

Прежде чем перейти к способам хранения данных, вспомним устройство контейнеров. Это поможет лучше понять основную тему.

Контейнер создаётся из образа, в котором есть всё для начала его работы. Но там не хранится и тем более не изменяется ничего важного. В любой момент приложение в контейнере может быть завершено, а контейнер уничтожен, и это нормально. Контейнер отработал — выкидываем его и собираем новый. Если пользователь загрузил в приложение картинку, то при замене контейнера она удалится.

На схеме показано устройство контейнера, запущенного из образа Ubuntu 15.04. Контейнер состоит из пяти слоёв: четыре из них принадлежат образу, и лишь один — самому контейнеру. Слои образа доступны только для чтения, слой контейнера — для чтения и для записи. Если при работе приложения какие-то данные будут изменяться, они попадут в слой контейнера. Но при уничтожении контейнера слой будет безвозвратно потерян, и все данные вместе с ним.

В идеальном мире Docker используют только для запуска stateless-приложений, которые не читают и не сохраняют данные о своём состоянии и готовы в любой момент завершиться. Однако в реальности большинство программ относятся к категории stateful, то есть требуют сохранения данных между перезапусками.

Поэтому нужны способы сделать так, чтобы важные изменяемые данные не зависели от эфемерности контейнеров и, как бонус, были доступными сразу из нескольких мест.

В Docker есть несколько способов хранения данных. Наиболее распространенные:

  • тома хранения данных (docker volumes),
  • монтирование каталогов с хоста (bind mount).

Особые типы хранения:

  • именованные каналы (named pipes, только в Windows),
  • монтирование tmpfs (только в Linux).

На схеме показаны самые популярные типы хранения данных для Linux: в памяти (tmpfs), в файловой системе хоста (bind mount), в томе Docker (docker volumes). Разберём каждый вариант.

Тома (docker volumes)

Тома — рекомендуемый разработчиками Docker способ хранения данных. В Linux тома находятся по умолчанию в /var/lib/docker/volumes/. Другие программы не должны получать к ним доступ напрямую, только через контейнер.

Тома создаются и управляются средствами Docker: командой docker volume create, через указание тома при создании контейнера в Dockerfile или docker-compose.yml.

В контейнере том видно как обычный каталог, который мы определяем в Dockerfile. Тома могут быть с именами или без — безымянным томам Docker сам присвоит имя.

Один том может быть примонтирован одновременно в несколько контейнеров. Когда никто не использует том, он не удаляется, а продолжает существовать. Команда для удаления томов: docker volume prune.

Можно выбрать специальный драйвер для тома и хранить данные не на хосте, а на удалённом сервере или в облаке.

Для чего стоит использовать тома в Docker:

  • шаринг данных между несколькими запущенными контейнерами,
  • решение проблемы привязки к ОС хоста,
  • удалённое хранение данных,
  • бэкап или миграция данных на другой хост с Docker (для этого надо остановить все контейнеры и скопировать содержимое из каталога тома в нужное место).

Монтирование каталога с хоста (bind mount)

Это более простая концепция: файл или каталог с хоста просто монтируется в контейнер.

Используется, когда нужно пробросить в контейнер конфигурационные файлы с хоста. Например, именно так в контейнерах реализуется DNS: с хоста монтируется файл /etc/resolv.conf.

Другое очевидное применение — в разработке. Код находится на хосте (вашем ноутбуке), но исполняется в контейнере. Вы меняете код и сразу видите результат. Это возможно, так как процессы хоста и контейнера одновременно имеют доступ к одним и тем же данным.

Особенности bind mount:

  1. Запись в примонтированный каталог могут вести программы как в контейнере, так и на хосте. Это значит, есть риск случайно затереть данные, не понимая, что с ними работает контейнер.
  2. Лучше не использовать в продакшене. Для продакшена убедитесь, что код копируется в контейнер, а не монтируется с хоста.
  3. Для успешного монтирования указывайте полный путь к файлу или каталогу на хосте.
  4. Если приложение в контейнере запущено от root, а совместно используется каталог с ограниченными правами, то в какой-то момент может возникнуть проблема с правами на файлы и невозможность что-то удалить без использования sudo.

Когда использовать тома, а когда монтирование с хоста

Volume Bind mount
Просто расшарить данные между контейнерами. Пробросить конфигурацию с хоста в контейнер.
У хоста нет нужной структуры каталогов. Расшарить исходники и/или уже собранные приложения.
Данные лучше хранить не локально (а в облаке, например). Есть стабильная структура каталогов и файлов, которую нужно расшарить между контейнерами.

Монтирование tmpfs

Tmpfs — временное файловое хранилище. Это некая специально отведённая область в оперативной памяти компьютера. Из определения выходит, что tmpfs — не лучшее хранилище для важных данных. Так оно и есть: при остановке или перезапуске контейнера сохранённые в tmpfs данные будут навсегда потеряны.

На самом деле tmpfs нужно не для сохранения данных, а для безопасности, полученные в ходе работы приложения чувствительные данные безвозвратно исчезнут после завершения работы контейнера. Бонусом использования будет высокая скорость доступа к информации.

Например, приложение в контейнере тормозит из-за того, что в ходе работы активно идут операции чтения-записи, а диски на хосте не очень быстрые. Если вы не уверены, в какой каталог идёт эта нагрузка, можно применить к запущенному контейнеру команду docker diff . И вот этот каталог смонтировать как tmpfs, таким образом перенеся ввод-вывод с диска в оперативную память.

Такое хранилище может одновременно работать только с одним контейнером и доступно только в Linux.

Общие советы по использованию томов

Монтирование в непустые директории

Если вы монтируете пустой том в каталог контейнера, где уже есть файлы, то эти файлы не удалятся, а будут скопированы в том. Этим можно пользоваться, когда нужно скопировать данные из одного контейнера в другой.

Если вы монтируете непустой том или каталог с хоста в контейнер, где уже есть файлы, то эти файлы тоже не удалятся, а просто будут скрыты. Видно будет только то, что есть в томе или каталоге на хосте. Похоже на простое монтирование в Linux.

Монтирование служебных файлов

С хоста можно монтировать любые файлы, в том числе служебные. Например, сокет docker. В результате получится docker-in-docker: один контейнер запустится внутри другого. UPD: (*это не совсем так. mwizard в комментариях пояснил, что в таком случае родительский docker запустит sibling-контейнер). Выглядит как бред, но в некоторых случаях бывает оправдано. Например, при настройке CI/CD.

Монтирование /var/lib/docker

Разработчики Docker говорят, что не стоит монтировать с хоста каталог /var/lib/docker, так как могут возникнуть проблемы. Однако есть некоторые программы, для запуска которых это необходимо.

Ключ командной строки для Docker при работе с томами.

Для volume или bind mount:

Команды для управления томами в интерфейсе CLI Docker:

Создадим тестовый том:

Вот он появился в списке:

Команда inspect выдаст примерно такой список информации в json:

Попробуем использовать созданный том, запустим с ним контейнер:

После самоуничтожения контейнера запустим другой и подключим к нему тот же том. Проверяем, что в нашем файле:

То же самое, отлично.

Теперь примонтируем каталог с хоста:

Docker не любит относительные пути, лучше указывайте абсолютные!

Теперь попробуем совместить оба типа томов сразу:

Отлично! А если нам нужно передать ровно те же тома другому контейнеру?

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

Создавать том заранее необязательно, всё сработает в момент запуска docker run:

Посмотрим теперь на список томов:

Ещё немного усложним команду запуска, создадим анонимный том:

Такой том самоуничтожится после выхода из контейнера, так как мы указали ключ –rm.

Если этого не сделать, давайте проверим что будет:

Хозяйке на заметку: тома (как образы и контейнеры) ограничены значением настройки dm.basesize, которая устанавливается на уровне настроек демона Docker. Как правило, что-то около 10Gb. Это значение можно изменить вручную, но потребуется перезапуск демона Docker.

При запуске демона с ключом это выглядит так:

Однажды увеличив значение, его уже нельзя просто так уменьшить. При запуске Docker выдаст ошибку.

Если вам нужно вручную очистить содержимое всех томов, придётся удалять каталог, предварительно остановив демон:

Если вам интересно узнать подробнее о работе с данными в Docker и других возможностях технологии, приглашаем на двухдневный онлайн-интенсив в феврале. Будет много практики.

Автор статьи: Александр Швалов, практикующий инженер Southbridge, Certified Kubernetes Administrator, автор и разработчик курсов Слёрм.

Источник

Читайте также:  Windows macbook загрузиться с диска
Оцените статью