What is docker volume
What is docker volume
Manage data in Docker
Estimated reading time: 9 minutes
By default all files created inside a container are stored on a writable container layer. This means that:
Docker has two options for containers to store files on the host machine, so that the files are persisted even after the container stops: volumes, and bind mounts.
Docker also supports containers storing files in-memory on the the host machine. Such files are not persisted. If you’re running Docker on Linux, tmpfs mount is used to store files in the host’s system memory. If you’re running Docker on Windows, named pipe is used to store files in the host’s system memory.
Keep reading for more information about persisting data or taking advantage of in-memory files.
Choose the right type of mount
No matter which type of mount you choose to use, the data looks the same from within the container. It is exposed as either a directory or an individual file in the container’s filesystem.
An easy way to visualize the difference among volumes, bind mounts, and tmpfs mounts is to think about where the data lives on the Docker host.
Volumes are stored in a part of the host filesystem which is managed by Docker ( /var/lib/docker/volumes/ on Linux). Non-Docker processes should not modify this part of the filesystem. Volumes are the best way to persist data 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 modify them at any time.
tmpfs mounts are stored in the host system’s memory only, and are never written to the host system’s filesystem.
More details about mount types
Volumes: Created and managed by Docker. You can create a volume explicitly using the docker volume create command, or Docker can create a volume during container or service creation.
When you create a volume, it is stored within a directory on the Docker host. When you mount the volume into a container, this directory is what is mounted into the container. This is similar to the way that bind mounts work, except that volumes are managed by Docker and are isolated from the core functionality of the host machine.
When you mount a volume, it may be named or anonymous. Anonymous volumes are not given an explicit name when they are first mounted into a container, so Docker gives them a random name that is guaranteed to be unique within a given Docker host. Besides the name, named and anonymous volumes behave in the same ways.
Volumes also support the use of volume drivers, which allow you to store your data on remote hosts or cloud providers, among other possibilities.
Bind mounts: Available 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 full path on the host machine. 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.
Bind mounts allow access to sensitive files
One side effect of using bind mounts, for better or for worse, is that you can change the host filesystem via processes running in a container, including creating, modifying, or deleting important system files or directories. This is a powerful ability which can have security implications, including impacting non-Docker processes on the host system.
tmpfs mounts: A tmpfs mount is not persisted on disk, either on the Docker host or within a container. It can be used by a container during the lifetime of the container, to store non-persistent state or sensitive information. For instance, internally, swarm services use tmpfs mounts to mount secrets into a service’s containers.
named pipes: An npipe mount can be used for communication between the Docker host and a container. Common use case is to run a third-party tool inside of a container and connect to the Docker Engine API using a named pipe.
Good use cases for volumes
Volumes are the preferred way to persist data in Docker containers and services. Some use cases for volumes include:
Sharing data among multiple running containers. If you don’t explicitly create it, a volume is created the first time it is mounted into a container. When that container stops or is removed, the volume still exists. Multiple containers can mount the same volume simultaneously, either read-write or read-only. Volumes are only removed when you explicitly remove them.
When the Docker host is not guaranteed to have a given directory or file structure. Volumes help you decouple the configuration of the Docker host from the container runtime.
When you want to store your container’s data on a remote host or a cloud provider, rather than locally.
When you need to back up, restore, or migrate data from one Docker host to another, volumes are a better choice. You can stop containers using the volume, then back up the volume’s directory (such as /var/lib/docker/volumes/ ).
When your application requires high-performance I/O on Docker Desktop. Volumes are stored in the Linux VM rather than the host, which means that the reads and writes have much lower latency and higher throughput.
When your application requires fully native file system behavior on Docker Desktop. For example, a database engine requires precise control over disk flushing to guarantee transaction durability. Volumes are stored in the Linux VM and can make these guarantees, whereas bind mounts are remoted to macOS or Windows, where the file systems behave slightly differently.
Good use cases for bind mounts
In general, you should use volumes where possible. Bind mounts are appropriate for the following types of use case:
Sharing configuration files from the host machine to containers. This is how Docker provides DNS resolution to containers by default, by mounting /etc/resolv.conf from the host machine into each container.
Sharing source code or build artifacts between a development environment on the Docker host and a container. For instance, you may mount a Maven target/ directory into a container, and each time you build the Maven project on the Docker host, the container gets access to the rebuilt artifacts.
If you use Docker for development this way, your production Dockerfile would copy the production-ready artifacts directly into the image, rather than relying on a bind mount.
When the file or directory structure of the Docker host is guaranteed to be consistent with the bind mounts the containers require.
Good use cases for tmpfs mounts
tmpfs mounts are best used for cases when you do not want the data to persist either on the host machine or within the container. This may be for security reasons or to protect the performance of the container when your application needs to write a large volume of non-persistent state data.
Tips for using bind mounts or volumes
If you use either bind mounts or volumes, keep the following in mind:
If you mount an empty volume into a directory in the container in which files or directories exist, these files or directories are propagated (copied) into the volume. Similarly, if you start a container and specify a volume which does not already exist, an empty volume is created for you. This is a good way to pre-populate data that another container needs.
Search Results
No Results
Filters
Understanding Docker Volumes
Files (and other data) stored within a Docker container does not persist if the container is deleted. To overcome this, Docker volumes and bind mounts can be used. This guide discusses using Docker volumes as a way to store persistent data. Think of volumes as an external hard drive; if the internal hard drive is erased, the external hard drive still retain its own data. Volumes are stored on the host and independent of any container or image. They can be mounted to different containers as needed and, since volumes are separate from the image, they do not increase the image size.
Before You Begin
If you have not already done so, create a Linode account and Compute Instance. See our Getting Started with Linode and Creating a Compute Instance guides.
Follow our Setting Up and Securing a Compute Instance guide to update your system. You may also wish to set the timezone, configure your hostname, create a limited user account, and harden SSH access.
Install Docker on your system.
This guide assumes you are comfortable using the Linux command-line. See Using the terminal.
Creating a Docker Volume
To start understanding Docker Volumes, you’ll need a volume to work on.
Log in to your Linode (or other Linux server) through either SSH or Lish.
Create a volume by entering the following command, replacing example_volume with the label for your volume.
Verify the volume has been created.
The output should look like this:
Inspecting a Docker Volume
If you want to look at more details about a volume, you can use the docker volume inspect command:
The output should be similar to the following:
Mounting a Docker Volume to a Container
As an example, the following command mounts the volume named example_volume to the path /example_volume inside a container using the ubuntu image.
Copying and Sharing Files Between Containers
Docker Volumes also allow sharing between containers.
Mount the volume according to the instructions within Mounting a Docker Volume to a Container. Here is the example used previously:
Change the directory to the example_data directory.
Create a test file in the volume by entering the following touch command.
Then exit the container.
Now run another docker image with the same volume mounted. The debian image is used in the example below.
Within the new container (called “example_2” if using a command similar to the one above) container, navigate to the volume’s directory.
Enter ls to see the file.
Mounting a Directory from Your Linode to a Container
Instead of creating a new volume, you can also mount a directory from your Linode (or other system) to a Docker container. This is accomplished through bind mounts and is helpful when you want to store and access your a container’s files directly from your system. Compared to volumes, bind mounts have limited functionality.
Log in to your Linode (or other Linux server) through either SSH or Lish.
You are automatically logged in to the container. Navigate to your mount directory and view the files.
You should see any files you have stored within the local directory.
Further Reading
There’s a great deal more to Docker Volumes than we can go into here, and everyone’s use case will be different. However, two great places to review more about this are at Docker’s Docs site itself:
More Information
You may wish to consult the following resources for additional information on this topic. While these are provided in the hope that they will be useful, please note that we cannot vouch for the accuracy or timeliness of externally hosted materials.
This page was originally published on Friday, August 13, 2021.
Хранение данных в Docker
Важная характеристика Docker-контейнеров — эфемерность. В любой момент контейнер может рестартовать: завершиться и вновь запуститься из образа. При этом все накопленные в нём данные будут потеряны. Но как в таком случае запускать в Docker приложения, которые должны сохранять информацию о своём состоянии? Для этого есть несколько инструментов.
В этой статье рассмотрим docker volumes, bind mount и tmpfs, дадим советы по их использованию, проведём небольшую практику.
Особенности работы контейнеров
Прежде чем перейти к способам хранения данных, вспомним устройство контейнеров. Это поможет лучше понять основную тему.
Контейнер создаётся из образа, в котором есть всё для начала его работы. Но там не хранится и тем более не изменяется ничего важного. В любой момент приложение в контейнере может быть завершено, а контейнер уничтожен, и это нормально. Контейнер отработал — выкидываем его и собираем новый. Если пользователь загрузил в приложение картинку, то при замене контейнера она удалится.
На схеме показано устройство контейнера, запущенного из образа Ubuntu 15.04. Контейнер состоит из пяти слоёв: четыре из них принадлежат образу, и лишь один — самому контейнеру. Слои образа доступны только для чтения, слой контейнера — для чтения и для записи. Если при работе приложения какие-то данные будут изменяться, они попадут в слой контейнера. Но при уничтожении контейнера слой будет безвозвратно потерян, и все данные вместе с ним.
В идеальном мире Docker используют только для запуска stateless-приложений, которые не читают и не сохраняют данные о своём состоянии и готовы в любой момент завершиться. Однако в реальности большинство программ относятся к категории stateful, то есть требуют сохранения данных между перезапусками.
Поэтому нужны способы сделать так, чтобы важные изменяемые данные не зависели от эфемерности контейнеров и, как бонус, были доступными сразу из нескольких мест.
В Docker есть несколько способов хранения данных. Наиболее распространенные:
Особые типы хранения:
На схеме показаны самые популярные типы хранения данных для 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:
Монтирование каталога с хоста (bind mount)
Это более простая концепция: файл или каталог с хоста просто монтируется в контейнер.
Используется, когда нужно пробросить в контейнер конфигурационные файлы с хоста. Например, именно так в контейнерах реализуется DNS: с хоста монтируется файл /etc/resolv.conf.
Другое очевидное применение — в разработке. Код находится на хосте (вашем ноутбуке), но исполняется в контейнере. Вы меняете код и сразу видите результат. Это возможно, так как процессы хоста и контейнера одновременно имеют доступ к одним и тем же данным.
Особенности bind mount:
Когда использовать тома, а когда монтирование с хоста
Volume | Bind mount |
---|---|
Просто расшарить данные между контейнерами. | Пробросить конфигурацию с хоста в контейнер. |
У хоста нет нужной структуры каталогов. | Расшарить исходники и/или уже собранные приложения. |
Данные лучше хранить не локально (а в облаке, например). | Есть стабильная структура каталогов и файлов, которую нужно расшарить между контейнерами. |
Монтирование tmpfs
Tmpfs — временное файловое хранилище. Это некая специально отведённая область в оперативной памяти компьютера. Из определения выходит, что tmpfs — не лучшее хранилище для важных данных. Так оно и есть: при остановке или перезапуске контейнера сохранённые в tmpfs данные будут навсегда потеряны.
На самом деле 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, автор и разработчик курсов Слёрм.
Изучаем Docker, часть 6: работа с данными
В сегодняшней части перевода серии материалов о Docker мы поговорим о работе с данными. В частности — о томах Docker. В этих материалах мы постоянно сравнивали программные механизмы Docker с разными съедобными аналогиями. Не будем отходить от этой традиции и здесь. Данные в Docker пусть будут специями. В мире существует множество видов специй, а в Docker — множество способов работы с данными.
Обратите внимание на то, что этот материал подготовлен с использованием движка Docker версии 18.09.1 и API версии 1.39.
Данные в Docker могут храниться либо временно, либо постоянно. Начнём с временных данных.
Временное хранение данные
В контейнерах Docker организовать работу с временными данными можно двумя способами.
По умолчанию файлы, создаваемые приложением, работающим в контейнере, сохраняются в слое контейнера, поддерживающем запись. Для того чтобы этот механизм работал, ничего специально настраивать не нужно. Получается дёшево и сердито. Приложению достаточно просто сохранить данные и продолжить заниматься своими делами. Однако после того как контейнер перестанет существовать, исчезнут и данные, сохранённые таким вот нехитрым способом.
Для хранения временных файлов в Docker можно воспользоваться ещё одним решением, подходящим для тех случаев, когда требуется более высокий уровень производительности, в сравнении с тем, который достижим при использовании стандартного механизма временного хранения данных. Если вам не нужно, чтобы ваши данные хранились бы дольше, чем существует контейнер, вы можете подключить к контейнеру tmpfs — временное хранилище информации, которое использует оперативную память хоста. Это позволит ускорить выполнение операций по записи и чтению данных.
Часто бывает так, что данные нужно хранить и после того, как контейнер прекратит существовать. Для этого нам пригодятся механизмы постоянного хранения данных.
Постоянное хранение данных
Существуют два способа, позволяющих сделать срок жизни данных большим срока жизни контейнера. Один из способов заключается в использовании технологии bind mount. При таком подходе к контейнеру можно примонтировать, например, реально существующую папку. Работать с данными, хранящимися в такой папке, смогут и процессы, находящиеся за пределами Docker. Вот как выглядят монтирование tmpfs и технология bind mount.
Монтирование tmpfs и bind mount
Минусы использования технологии bind mount заключаются в том, что её использование усложняет резервное копирование данных, миграцию данных, совместное использование данных несколькими контейнерами. Гораздо лучше для постоянного хранения данных использовать тома Docker.
Тома Docker
Том — это файловая система, которая расположена на хост-машине за пределами контейнеров. Созданием и управлением томами занимается Docker. Вот основные свойства томов Docker:
Создание томов
Тома можно создавать средствами Docker или с помощью запросов к API.
Вот инструкция в Dockerfile, которая позволяет создать том при запуске контейнера.
При использовании подобной инструкции Docker, после создания контейнера, создаст том, содержащий данные, которые уже имеются в указанном месте. Обратите внимание на то, что если вы создаёте том с использованием Dockerfile, это не освобождает вас от необходимости указать точку монтирования тома.
Создавать тома в Dockerfile можно и используя формат JSON.
Кроме того, тома можно создавать средствами командной строки во время работы контейнера.
Работа с томами из командной строки
▍Создание тома
Создать самостоятельный том можно следующей командой:
▍Выяснение информации о томах
Для того чтобы просмотреть список томов Docker, воспользуйтесь следующей командой:
Исследовать конкретный том можно так:
▍Удаление тома
Удалить том можно так:
Для того чтобы удалить все тома, которые не используются контейнерами, можно прибегнуть к такой команде:
Перед удалением томов Docker запросит у вас подтверждение выполнения этой операции.
Если том связан с каким-либо контейнером, такой том нельзя удалить до тех пор, пока не удалён соответствующий контейнер. При этом, даже если контейнер удалён, Docker не всегда это понимает. Если это случилось — можете воспользоваться следующей командой:
Она предназначена для очистки ресурсов Docker. После выполнения этой команды у вас должна появиться возможность удалить тома, статус которых до этого определялся неправильно.
Итоги
Вот полезные команды, которыми можно пользоваться при работе с томами Docker:
Уважаемые читатели! Какие материалы о Docker вы посоветовали бы изучить новичкам?
Docker Volume
By Sarabjeet Singh
Introduction to Docker Volume
Docker volume is a storage mechanism that is used for persistent data storage generated by Docker containers. Docker volumes are managed by Docker itself. It is better to store data in a volume rather than storing it in a container’s writable layer as it does not increase the size of the container; also, containers are ephemeral, which means container lifetime is short, and containers get destroyed, and so the data as well. Docker volume can be shared with more than one container.
Syntax:
Web development, programming languages, Software testing & others
docker volume COMMAND
Commands of Docker Volume
Below are the different commands of Docker Volume:
1. create: It is used to create new volumes.
2. ls: It is used to list all the volumes in a namespace.
3. inspect: It is used to know more about any of the volumes.
4. rm: It is used to remove any volume if it is no longer required.
5. prune: It is used to remove all unused volumes.
Command:
Output:
We can get more information about any command by using the ‘help’ option after the command as below:
Command:
Below is the example:
Command:
How Does Volume Work in Docker?
We use the ‘-v’ or ‘-volume’ option to mount the Docker volume to standalone containers, and the ‘–mount’ option is used for swarm services only. However, we can use the ‘–mount’ option with the standalone containers as well in Docker version 17.06 and newer. The ‘–mount’ is simpler than ‘-v’ as it is more explicit and verbose. We must use the ‘–mount’ flag while mounting the volume to the container if we want to specify a volume driver.
Let’s understand the syntax of each flag:
Below is the example:
Command:
In the above example, ‘my-vol’ is the name of the volume, and ‘/etc/’ is the folder inside the container, and access mode is read-only.
2. –mount: It has key-value pairs, and it is separated by commas.
Below keys are used in this option:
Examples to Implement Docker Volume
Below are the examples of Docker Volume:
Scenario: We will create a volume first and verify it, and then we will check the all details about the newly created volume. We will then mount this volume to a container and then create a test file in the container at the location where we mounted the volume. We will then mount the same volume to different containers and check the test file over there to verify it worked as expected. Let’s get started.
1. Create a new volume named ‘my-vol’ and list it as below.
docker volume create my-vol
docker volume ls
Output:
2. Check all details of this volume using the ‘inspect’ command as below:
Command:
docker volume inspect my-vol
Output:
Explanation: The ‘Mountpoint’ is the location where the files or folders going to store actually. So if we browse that location, there is nothing right now. we will populate the data after mounting it to any container; then, if we browse this location, we will get the files or folders over here that we have created at the mounting location in the container.
3. Now, mount this volume to a container using the ‘-v’ flag and connect to the container using the ‘docker exec’command, create a new test file ‘test.txt’. Stop and delete this container and create a new container and connect the same volume to this container. Again, execute this new container and check if the file is available or not in this newly created container as below:
Commands:
# echo “This is a test file” > test.txt
Output:
Explanation: In the above snapshot, we can see that the file is available even after the first container got destroyed.
4. If we want to see the above file without mounting it to any container as discussed in the explanation of point 2, then we have to browse the ‘Mountpoint’ of the volume as below:
Command:
sudo cat /var/lib/docker/volumes/my-vol/_data/test.txt
5. Let’s assume that this volume is no longer required and can be deleted; we can do so using the ‘rm’ command as below:
Command:
docker volume rm my-vol
Output:
6. If there are multiple volumes that need to be deleted, we use the ‘prune’ command to delete all unused volumes at once as below:
docker volume prune
Explanation: In the above example, we have created 3 new volumes and did not attach any container to them it so we can use the ‘prune’ command to delete all the three volumes at once.
Advantages of Docker Volume
Conclusion
Docker volumes are safe any easy way to store the data persistently. We also have a bind mount for persistent storage; however, it has less functionality compare to Docker volumes. We have discussed named volume, we also have anonymous volumes that do not have a specific source, and it is removed once the container got deleted.
Recommended Articles
This is a guide to Docker Volume. Here we discuss the Introduction of Docker Volume and its advantages along with its Examples and Code Implementation. You can also go through our other suggested articles to learn more –