Mac os docker raw

Disk utilization in Docker for Mac

Estimated reading time: 3 minutes

Docker Desktop stores Linux containers and images in a single, large “disk image” file in the Mac filesystem. This is different from Docker on Linux, which usually stores containers and images in the /var/lib/docker directory.

Where is the disk image file?

To locate the disk image file, select the Docker icon and then Preferences > Resources > Advanced.

The Advanced tab displays the location of the disk image. It also displays the maximum size of the disk image and the actual space the disk image is consuming. Note that other tools might display space usage of the file in terms of the maximum file size, and not the actual file size.

If the file is too big

If the disk image file is too big, you can:

  • move it to a bigger drive,
  • delete unnecessary containers and images, or
  • reduce the maximum allowable size of the file.

Move the file to a bigger drive

To move the disk image file to a different location:

Select Preferences > Resources > Advanced.

In the Disk image location section, click Browse and choose a new location for the disk image.

Click Apply & Restart for the changes to take effect.

Do not move the file directly in Finder as this can cause Docker Desktop to lose track of the file.

Delete unnecessary containers and images

Check whether you have any unnecessary containers and images. If your client and daemon API are running version 1.25 or later (use the docker version command on the client to check your client and daemon API versions), you can see the detailed space usage information by running:

Источник

Docker for Mac: reducing disk space

Docker for Mac is a desktop app which allows building, testing and running Dockerized apps on the Mac. Linux container images run inside a VM using a custom hypervisor called hyperkit – part of the Moby open-source project. The VM boots from an .iso and has a single writable disk image stored on the Mac’s filesystem in the

/Library/Containers/com.docker.docker/Data/com.docker.driver.amd64-linux directory. The filename is either Docker.qcow2 or Docker.raw , depending on the format. Over time this file can grow and become large. This post explains

  • what’s in the Docker.raw (or Docker.qcow2 );
  • why it grows (often unexpectedly); and
  • how to shrink it again.

What’s in the Docker.raw (or Docker.qcow)?

If a container creates or writes to a file then the effect depends on the path, for example:

  • If the path is on a tmpfs filesystem, the file is created in memory..
  • If the path is on a volume mapped from the host or from a remote server (via e.g. docker run -v or docker run —mount ) then the open / read / write /… calls are forwarded and the file is accessed remotely.
  • If the path is none of the above, then the operation is performed by the overlay filesystem, on top of an ext4 filesystem on top of the partition /dev/sda1 . The device /dev/sda is a (virtual) AHCI device, whose code is in the hyperkit ahci-hd driver. The hyperkit command-line has an entry -s 4,ahci-hd,/. /Docker.raw which configures hyperkit to emulate an AHCI disk device such that when the VM writes to sector x on the device, the data will be written to byte offset x * 512 in the file Docker.raw where 512 is the hard-coded sector size of the virtual disk device.

So the Docker.raw (or Docker.qcow2 ) contain image and container data, written by the Linux ext4 and overlay filesystems.

Why does the file keep growing?

If Docker is used regularly, the size of the Docker.raw (or Docker.qcow2 ) can keep growing, even when files are deleted.

To demonstrate the effect, first check the current size of the file on the host:

Note the use of -s which displays the number of filesystem blocks actually used by the file. The number of blocks used is not necessarily the same as the file “size”, as the file can be sparse.

Next start a container in a separate terminal and create a 1GiB file in it:

Back on the host check the file size again:

Note the increase in size from 9964528 to 12061704 , where the increase of 2097176 512 -byte sectors is approximately 1GiB, as expected. If you switch back to the alpine container terminal and delete the file:

then check the file on the host:

The file has not got any smaller! Whatever has happened to the file inside the VM, the host doesn’t seem to know about it.

Читайте также:  Обзор windows mac linux

Next if you re-create the “same” 1GiB file in the container again and then check the size again you will see:

It’s got even bigger! It seems that if you create and destroy files in a loop, the size of the Docker.raw (or Docker.qcow2 ) will increase up to the upper limit (currently set to 64 GiB), even if the filesystem inside the VM is relatively empty.

The explanation for this odd behaviour lies with how filesystems typically manage blocks. When a file is to be created or extended, the filesystem will find a free block and add it to the file. When a file is removed, the blocks become “free” from the filesystem’s point of view, but no-one tells the disk device. Making matters worse, the newly-freed blocks might not be re-used straight away – it’s completely up to the filesystem’s block allocation algorithm. For example, the algorithm might be designed to favour allocating blocks contiguously for a file: recently-freed blocks are unlikely to be in the ideal place for the file being extended.

Since the block allocator in practice tends to favour unused blocks, the result is that the Docker.raw (or Docker.qcow2 ) will constantly accumulate new blocks, many of which contain stale data. The file on the host gets larger and larger, even though the filesystem inside the VM still reports plenty of free space.

Aside: SSD drives have a similar problem

SSD drives suffer from the same phenomenon. SSDs are only able to erase data in large blocks (where the “erase block” size is different from the exposed sector size) and the erase operation is quite slow. The drive firmware runs a garbage collector, keeping track of which blocks are free and where user data is stored. To modify a sector, the firmware will allocate a fresh block and, to avoid the device filling up with almost-empty blocks containing only one sector, will consider moving some existing data into it.

If the filesystem writing to the SSD tends to favour writing to unused blocks, then creating and removing files will cause the SSD to fill up (from the point of view of the firmware) with stale data (from the point of view of the filesystem). Eventually the performance of the SSD will fall as the firmware has to spend more and more time compacting the stale data before it can free enough space for new data.

A TRIM command (or a DISCARD or UNMAP ) allows a filesystem to signal to a disk that a range of sectors contain stale data and they can be forgotten. This allows:

  • an SSD drive to erase and reuse the space, rather than spend time shuffling it around; and
  • Docker for Mac to deallocate the blocks in the host filesystem, shrinking the file.

So how do we make this work?

Automatic TRIM in Docker for Mac

In Docker for Mac 17.11 there is a containerd “task” called trim-after-delete listening for Docker image deletion events. It can be seen via the ctr command:

When an image deletion event is received, the process waits for a few seconds (in case other images are being deleted, for example as part of a docker system prune ) and then runs fstrim on the filesystem.

Returning to the example in the previous section, if you delete the 1 GiB file inside the alpine container

then run fstrim manually from a terminal in the host:

then check the file size:

The file is back to (approximately) it’s original size – the space has finally been freed!

The code

There are two separate implementations of TRIM in Docker for Mac: one for Docker.qcow2 and one for Docker.raw . On High Sierra running on an SSD, the default filesystem is APFS and we use Docker.raw by default. This is because APFS supports an API for deallocating blocks from inside a file, while HFS+ does not. On older versions of macOS and on non-SSD hardware we default to Docker.qcow2 which implements block deallocation in userspace which is more complicated and generally slower. Note that Apple hope to add support to APFS for fusion and traditional spinning disks in some future update – once this happens we will switch to Docker.raw on those systems as well.

Support for adding TRIM to hyperkit for Docker.raw was added in PR 158. When the Docker.raw file is opened it calls fcntl(F_PUNCHHOLE) on a zero-length region at the start of the file to probe whether the filesystem supports block deallocation. On HFS+ this will fail and we will disable TRIM, but on APFS (and possibly future filesystems) this succeeds and so we enable TRIM. To let Linux running in the VM know that we support TRIM we set some bits in the AHCI hardware identification message, specifically:

  • ATA_SUPPORT_RZAT : we guarantee to Read-Zero-After-TRIM (RZAT)
  • ATA_SUPPORT_DRAT : we guarantee Deterministic-Read-After-TRIM (DRAT) (i.e. the result of reading after TRIM won’t change)
  • ATA_SUPPORT_DSM_TRIM : we support the TRIM command

Once enabled the Linux kernel will send us TRIM commands which we implement with fcntl(F_PUNCHOLE) with the caveat that the sector size in the VM is currently 512, while the sector size on the host can be different (it’s probably 4096) which means we have to be careful with alignment.

Читайте также:  The best browser linux

The support for TRIM in Docker.qcow2 is via the Mirage qcow2 library. This library contains its own block garbage collector which manages a free list of TRIM’ed blocks within the file and then performs background compaction and erasure (similar to the firmware on an SSD). The GC must run concurrently and with lower priority than reads and writes from the VM, otherwise Linux will timeout and attempt to reset the AHCI controller (which unfortunately isn’t implemented fully).

The qcow2 format includes both data blocks and metadata blocks, where the metadata blocks contain references to other blocks. When performing a compaction of the file, care must be taken to flush copies of blocks to stable storage before updating references to them, otherwise the writes could be permuted leading to the reference update being persisted but not the data copy – corrupting the file. Since flushes are very slow (taking maybe 10ms), block copies are done in large batches to spread the cost. If the VM writes to one of the blocks being copied, then that block copy must be cancelled and retried later. All of this means that the code is much more complicated and much slower than the Docker.raw version; presumably the implementation of fcntl(F_PUNCHHOLE) in the macOS kernel operates only on the filesystem metadata and doesn’t involve any data copying!

Status in Docker for Mac releases

As of 2017-11-28 the latest Docker for Mac edge version is 17.11.0-ce-mac40 (20561) – automatic TRIM on image delete is enabled by default on both Docker.raw and Docker.qcow2 files (although the Docker.raw implementation is faster).

If you feel Docker for Mac is taking up too much space, first check how many images and containers you have with

  • docker image ls -a
  • docker ps -a

and consider deleting some of those images or containers, perhaps by running a docker system prune):

The automatic TRIM on delete should kick in shortly after the images are deleted and free the space on the host. Take care to measure the space usage with ls -s to see the actual number of blocks allocated by the files.

If you want to trigger a TRIM manually in other cases, then run

To try all this for yourself, get the latest edge version of Docker for Mac from the Docker Store. Let me know how you get on in the docker-for-mac channel of the Docker community slack. If you hit a bug, file an issue on docker/for-mac on GitHub.

Источник

Докер заполняет хранилище на macOS

(Сообщение создано 05 октября 2016 г.)

Я заметил, что каждый раз, когда я запускаю изображение и удаляю его, моя система не возвращается к исходному количеству доступного пространства.

Жизненный цикл, который я применяю к своим контейнерам:

[работает на терминале Mac по умолчанию]

Контейнеры, созданные из пользовательских образов, запускаемых из узла и стандартного Redis. Моя ОС — OSX 10.11.6.

В конце дня я вижу, что продолжаю терять Mbs. Как я могу столкнуться с этой проблемой?

РЕДАКТОР

2020 г., и проблема не устранена, и я оставляю это обновление для сообщества:

  • macOS 10.13.6
  • Движок Докера 18.9.2
  • Docker Desktop Cli 2.0.0.3

Самый простой способ обойти проблему — обрезать систему с помощью утилит Docker.

7 ответов

ВНИМАНИЕ!

По умолчанию тома не удаляются, чтобы предотвратить удаление важных данных, если в настоящее время нет контейнера, использующего том. Используйте флаг —volumes при запуске команды для сокращения томов:

Теперь у Docker есть одна команда для этого:

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

Эти три команды очищают все, что не используется:

  • docker rm $(docker ps -f status=exited -aq) — удалить остановленные контейнеры
  • docker rmi $(docker images -f «dangling=true» -q) — удалить слои изображения, которые не используются ни в каких изображениях
  • docker volume rm $(docker volume ls -qf dangling=true) — удалить тома, которые не используются ни одной емкостью.

Их можно запускать безопасно, они не удаляют слои изображений, на которые ссылаются изображения, или тома данных, которые используются контейнерами. Вы можете присвоить им псевдоним и / или поместить их в задание CRON для регулярной очистки локального диска.

Также стоит упомянуть, что размер файла docker.qcow2 (или Docker.raw на High Sierra с файловой системой Apple) может показаться очень большим (

64 ГБ), больше, чем есть на самом деле, при использовании следующей команды:

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

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

У Docker на Mac есть дополнительная проблема, от которой страдает множество людей: файл docker.qcow2 может увеличиваться в размерах (до 64 ГБ) и никогда не уменьшится сам по себе.

Читайте также:  Кмс активатор windows 10 рутор

Как указано в одном из ответов djs55, это планируется исправить, но это не быстрое решение. Цитата:

.Qcow2 предоставляется виртуальной машине как блочное устройство с максимальным размером 64 ГБ. Поскольку новые файлы создаются в файловой системе контейнерами, новые сектора записываются на блочное устройство. Эти новые секторы добавляются к файлу .qcow2, вызывая его увеличение в размере до тех пор, пока он в конечном итоге не станет полностью выделенным. Он перестает расти, когда достигает этого максимального размера.

Мы надеемся исправить это в несколько этапов: (обратите внимание, что это все еще на стадии планирования / проектирования, но я надеюсь, что это даст вам представление)

1) мы переключимся на протокол подключения, который поддерживает TRIM, и реализуем отслеживание свободных блоков в файле метаданных рядом с qcow2. Мы создадим инструмент уплотнения, который можно будет запустить в автономном режиме для сжатия диска (немного похоже на qemu-img convert, но без dd if = / dev / zero, и он должен быть быстрым, потому что он уже будет знать, где находится пустое пространство )

2) автоматизируем запуск инструмента сжатия после перезагрузки виртуальной машины, если он будет достаточно быстрым

3) мы перейдем на онлайн-компактор (который немного похож на сборщик мусора на языке программирования)

Мы также стремимся сделать максимальный размер настраиваемого .qcow2. Возможно, 64 ГБ слишком велик для некоторых сред, и меньшее ограничение может помочь?

Обновление 2019 : с момента публикации этого ответа в Docker для Mac было внесено много обновлений, чтобы помочь смягчить проблемы (в частности: поддержка другой файловой системы).

Очистка все еще не полностью автоматическая, время от времени вам может потребоваться обрезка. Для одной команды, которая может помочь очистить дисковое пространство, см. ответ Чжунцзяцзе.

Есть несколько вариантов ограничения дискового пространства докеров, я бы начал с ограничения / ротации журналов: Журналы контейнера Docker занимают все мое дисковое пространство

Например. если у вас установлена ​​последняя версия докера, вы можете запустить ее с параметром —log-opt max-size=50m для каждого контейнера. Кроме того, если у вас есть старые неиспользуемые контейнеры, вы можете просмотреть журналы докеров, которые находятся по адресу /var/lib/docker/containers/*/*-json.log .

Почему файл продолжает расти?

Если Docker используется регулярно, размер Docker.raw (или Docker.qcow2 ) может продолжать расти, даже если файлы удалены.

Чтобы продемонстрировать эффект, сначала проверьте текущий размер файла на хосте:

Обратите внимание на использование -s , которое отображает количество блоков файловой системы, фактически используемых файлом. Количество используемых блоков не обязательно совпадает с «размером» файла, так как файл может быть разреженным .

Затем запустите контейнер в отдельном терминале и создайте в нем файл размером 1ГиБ:

Вернувшись на хост, снова проверьте размер файла:

Обратите внимание на увеличение размера с 9964528 до 12061704 , где увеличение 2097176 512 — байтовых секторов составляет примерно 1 ГБ, как и ожидалось. Если вы снова переключитесь на контейнерный терминал alpine и удалите файл:

Затем проверьте файл на хосте:

Файл меньше не стал! Что бы ни случилось с файлом внутри виртуальной машины, хост, похоже, не знает об этом.

Затем, если вы снова создадите «тот же» файл 1GiB в контейнере, а затем снова проверите размер, вы увидите:

Он стал еще больше! Кажется, что если вы создаете и уничтожаете файлы в цикле, размер Docker.raw (или Docker.qcow2 ) увеличится до верхнего предела (в настоящее время установлено 64 ГиБ), даже если файловая система внутри виртуальная машина относительно пуста.

Такое странное поведение объясняется тем, как файловые системы обычно управляют блоками. Когда файл должен быть создан или расширен, файловая система найдет свободный блок и добавит его в файл. Когда файл удаляется, блоки становятся «свободными» с точки зрения файловой системы, но никто не сообщает об этом дисковому устройству. Что еще хуже, недавно освобожденные блоки не могут быть повторно использованы сразу — это полностью зависит от алгоритма распределения блоков файловой системы. Например, алгоритм может быть разработан таким образом, чтобы способствовать непрерывному распределению блоков для файла: недавно освобожденные блоки вряд ли окажутся в идеальном месте для расширяемого файла.

Поскольку на практике распределитель блоков предпочитает неиспользуемые блоки, в результате Docker.raw (или Docker.qcow2 ) будет постоянно накапливать новые блоки, многие из которых содержат устаревшие данные. Файл на хосте становится все больше и больше, хотя файловая система внутри виртуальной машины по-прежнему сообщает о большом количестве свободного места.

ОТДЕЛКА

Команда TRIM (или DISCARD или UNMAP ) позволяет файловой системе сигнализировать диску, что диапазон секторов содержит устаревшие данные, и о них можно забыть. Это позволяет:

  • SSD-накопитель для стирания и повторного использования пространства, вместо того, чтобы тратить время на его перетасовку; а также
  • Docker для Mac, чтобы освободить блоки в файловой системе хоста, сжав файл.

Итак, как нам заставить это работать?

Автоматическая TRIM в Docker для Mac

В Docker для Mac 17.11 есть containerd «задача», называемая trim-after-delete прослушивание событий удаления образа Docker. Это можно увидеть с помощью команды ctr :

Когда получено событие удаления изображения, процесс ожидает в течение нескольких секунд (в случае удаления других изображений, например, как часть docker system prune), а затем запускает fstrim в файловой системе.

Возвращаясь к примеру из предыдущего раздела, если вы удалите файл размером 1 ГиБ внутри контейнера alpine

Затем запустите fstrim вручную с терминала на хосте:

Затем проверьте размер файла:

Файл вернулся к (приблизительно) исходному размеру — наконец-то освободилось место!

Источник

Оцените статью