- Docker на macOS
- Использование MacOS машины как хоста
- Современный способ (Docker for Mac)
- Старый способ (Docker Toolbox)
- Другой гипервизор
- Использование облачных сервисов и управление через Docker API
- Другая машина (VPS, VDS, любой «соседний» ПК на Linux или ВМ)
- IaaS Azure, AWS, OpenStack и прочие
- Дополнительные драйверы для docker-machine
- Автодополнение Docker для шелла
- Homebrew
- Только установка docker (CLI), docker-machine, docker-compose
- Docker hyperkit mac os
- Latest commit
- Git stats
- Files
- README.md
- About
- Diagnosing high CPU usage on Docker for Mac
- Docker stats
- iosnoop
- dtrace (dtruss)
- Update: top on Docker host
- Update: running dtrace scripts of most common stack traces
- Related issues
- 6 Answers 6
Docker на macOS
Немного о консольных составляющих
docker — утилита, общающаяся через сокет с хостом Docker ( docker daemon ). Является клиентом.
docker-machine — средство для управления машинами с Docker, а так же их создания. Расширярется так называемыми драйверами.
docker-compose — утилита для определения и выполнения кросс-контейнерных приложений. Позволяет объединить и настроить связку отдельных приложений в контейнерах, например, для веб-сервера: nginx, MySQL, PHP.
Использование MacOS машины как хоста
Самый очевидный способ использования Docker на Mac, учитывая, что Docker может создавать контейнеры только на ядре Linux, это использование виртуальной машины. Уже самые первые Mac на платформе Intel позволяли использовать паравиртуализацию и аппаратное ускорение для запуска виртуальных машин, но родного гипервизора не было: различные производители ПО, вроде VMware и Parralells заняли нишу гипервизоров на MacOS. Конечно же, было еще и бесплатное решение от Oracle (Virtual Box), но оно не такое удобное. В любом случае эти гипервизоры были сделаны в виде расширения ядра и порой были не очень стабильны. Начиная с Yosemite Apple добавили Hypervisor.framework, представляющий из себя API для создания HVM (аппаратных виртуальных машин). Сложно назвать это средство полноценным гипервизором, но первое достаточно массовое решение на нем — xhyve и Veertu. xhyve — гипервизор, портированный с FreeBSD и позволяет запускать Linux-машины.
До появления Hypervisor.framework и проекта xhyve предлагалось запускать Docker в виртуальной машине, используя гипервизор Virtual Box или любой другой (при помощи утилиты docker-machine у которой есть свои «драйверы», позволяющие автоматизировать создание, запуск и работу с виртуальными машинами) из предложенных. Это legacy-решение, но оно до сих пор поддерживается.
Современное же решение – это запуск виртуальной машины с использованием встроенного в MacOS процесса виртуализации. Docker назвали его HyperKit и его кодовая база практически полностью основана на проекте xhyve.
Старый способ (Docker Toolbox), как и драйверы для многих гипервизоров, разворачивают в стороннем гипервизоре образ ОС Boot2Docker.
Современный способ (Docker for Mac)
Данный способ поддерживает только Yosemite 10.10.3 и старше, но рекомендуется El Capitan и выше. Используется HyperKit, встроенная в MacOS виртуализация.
Установка проста и описана на странице Docker for Mac. Необходимо скачать DMG-контейнер, перетащить его содержимое и запустить Docker. Будут установлены консольные утилиты (docker, docker-machine, docker-compose), а также графическая оболочка для управления виртуальной машиной, в которой запущен Docker и бета-версия официальной графической утилиты для управления контейнерами Kitematic. Сразу же после этого можно использовать Docker в полную силу.
Старый способ (Docker Toolbox)
Установка так же простая и описана на странице Docker Toolbox. Установщик сам установит все необходимое, в том числе и гипервизор Oracle VirtualBox. Управлять можно с приложения Kitematic и терминала. Специально сделан шорткат, который можно найти в Launchpad и который позволит подключиться к виртуальной машине. Его же необходимо будет запустить в первый раз, так как он сам сделает виртуальную машину и настроит ее. Далее можно подключаться просто с терминала, выполнив вначале eval $(docker-machine env dev) , после чего можно общаться с docker посредством команды docker .
Рекомендуется настроить виртуальную машину Virtual Box так, чтобы она имела статический IP адрес, но была за NAT. В таком случае можно будет запускать контейнер через docker-machine или VBoxManage , либо с графического интерфейса, после чего работать с ней с обычного терминала.
Другой гипервизор
Для использования другого гипервизора необходимо установить комплект консольных утилит (docker, docker-mahine, docker-compose[^*]). Сделать это можно, установив Docker любым из способов, описанных выше, либо установив консольные утилиты через Homebrew. Кроме того, если уже установлен Virtual Box и Homebrew, то установив через него утилиты можно сделать виртуальные машины для Docker и управлять самим Docker.
[^*]: Необязателен для использования, зависит от поставленной задачи.
Чтобы создать виртуальную машину через docker-machine необходимо изучить документацию к необходимому драйверу. Для тех, что присутствуют по умолчанию, можно посмотреть в официальной документации Docker. Например, для создания виртуальной машины в VMware Fusion необходимо выполнить
После чего для для управления через docker необходимо выполнить
Чтобы точно знать, что мы управляем нужной машиной всегда можно набрать
Использование облачных сервисов и управление через Docker API
Другая машина (VPS, VDS, любой «соседний» ПК на Linux или ВМ)
Чтобы управлять Docker на любой другой машине необходимо воспользоваться драйвером Generic. Он позволит добавить через SSH с ключом или паролем любую машину в реестр docker-toolbox для удобства дальнейшего подключения через утилиту docker .
Почитать по управлению с по мощью драйвера можно в отдельной статье.
IaaS Azure, AWS, OpenStack и прочие
Используя необходимый драйвер в docker-machine можно создать виртуальную машину с Docker на практически любом популярном IaaS сервисе.
Для примера разберем MS Azure в отдельной статье.
Дополнительные драйверы для docker-machine
Если хочется использовать Docker с xhyve или же Parallels, Vultr, то можно поставить драйверы их Homebrew.
Автодополнение Docker для шелла
Чтобы было наиболее удобно управлять Docker имеет смысл установить автодополнение для шела. К сожалению, в версии для Mac оно не поставляется ни в одном варианте.
Homebrew
Если еще не установлен менеджер пакетов brew, то стоит его установить.
/usr/bin/ruby -e «$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)»
Лучше использовать шел ZSH. Он легко расширяется модулями и для него больше хороших модулей автодополнения. <==Почитать про устновку можно в отдельной статье==>.
Установить автодополнение для docker, docker-machine, docker-compose не составит труда.
brew install docker-completion docker-machine-completion docker-compose-completion
После установки чтобы автодополнение работало проще всего открыть новую вкладку терминала и проверить работоспособность.
Для установки автодополнения для шела bash необходимо выполнить после установки с Homebrew.
Только установка docker (CLI), docker-machine, docker-compose
Используя Homebrew можно установить указанные выше утилиты для управления docker на любой виртуальной (иди другой) машине без лишних утилит. Можно добавить машину в docker-machine и легко получить к ней доступ через команду eval $(docker-machine env machinename) , после чего управлять ей через docker .
Copyright © 2017 Александр Пинегин aka Bloody Foxy
Источник
Docker hyperkit mac os
A toolkit for embedding hypervisor capabilities in your application
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
HyperKit is a toolkit for embedding hypervisor capabilities in your application. It includes a complete hypervisor, based on xhyve/bhyve, which is optimized for lightweight virtual machines and container deployment. It is designed to be interfaced with higher-level components such as the VPNKit and DataKit.
HyperKit currently only supports macOS using the Hypervisor.framework. It is a core component of Docker Desktop for Mac.
- OS X 10.10.3 Yosemite or later
- a 2010 or later Mac (i.e. a CPU that supports EPT)
If you are using a version of Hyperkit which is embedded into a higher level application (e.g. Docker Desktop for Mac) then please report any issues against that higher level application in the first instance. That way the relevant team can triage and determine if the issue lies in Hyperkit and assign as necessary.
If you are using Hyperkit directly then please report issues against this repository.
The resulting binary will be in build/hyperkit
To enable qcow support in the block backend an OCaml OPAM development environment is required with the qcow module available. A suitable environment can be setup by installing opam and libev via brew and using opam to install the appropriate libraries:
opam config env must be evaluated each time prior to building hyperkit so the build will find the ocaml environment.
Any previous pin of mirage-block-unix or qcow should be removed with the commands:
HyperKit defines a number of static DTrace probes to simplify investigation of performance problems. To list the probes supported by your version of HyperKit, type the following command while HyperKit VM is running:
Refer to scripts in dtrace/ directory for examples of possible usage and available probes.
Relationship to xhyve and bhyve
HyperKit includes a hypervisor derived from xhyve, which in turn was derived from bhyve. See the original xhyve README which incorporates the bhyve README.
We try to avoid deviating from these upstreams unnecessarily in order to more easily share code, for example the various device models/emulations should be easily shareable.
Reporting security issues
The maintainers take security seriously. If you discover a security issue, please bring it to their attention right away!
Please DO NOT file a public issue, instead send your report privately to security@docker.com.
Security reports are greatly appreciated and we will publicly thank you for it. We also like to send gifts—if you’re into Docker schwag, make sure to let us know. We currently do not offer a paid security bounty program, but are not ruling it out in the future.
Copyright and license
Copyright the authors and contributors. See individual source files for details.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS «AS IS» AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
About
A toolkit for embedding hypervisor capabilities in your application
Источник
Diagnosing high CPU usage on Docker for Mac
How do I diagnose the cause of Docker on MacOS, specifically com.docker.hyperkit using 100% of CPU?
Docker stats
Docker stats shows all the running containers have low CPU, memory, net IO and block IO.
iosnoop
iosnoop shows that com.docker.hyperkit performs about 50 writes per second totaling 500KB per second to the file Docker.qcow2 . According to What is Docker.qcow2?, Docker.qcow2 is a sparse file that’s the persistent storage for all Docker containers.
In my case the file isn’t that sparse. The physical size matches the logical size.
dtrace (dtruss)
dtruss sudo dtruss -p $DOCKER_PID shows a large number of psynch_cvsignal and psynch_cvwait calls.
Update: top on Docker host
The CPU usage on docker embedded host is
3%. CPU usage on my MacBook was
100%. So, the docker embedded host isn’t causing the CPU usage spike.
Update: running dtrace scripts of most common stack traces
Stack traces from the dtrace scripts in the answer below: https://stackoverflow.com/a/58293035/30900.
These kernel stack traces look innocuous.
The most common stack traces in user space over 17 seconds clearly implicate com.docker.hyperkit. There 1365 stack traces in 17 seconds in which com.docker.hyperkit created threads which averages to 80 threads per second.
Related issues
Github — docker/for-mac: com.docker.hyperkit 100% cpu usage is back again #3499 . One comment suggests adding volume caching described here: https://www.docker.com/blog/user-guided-caching-in-docker-for-mac/. I tried this and got a small
10% reduction in CPU usage.
6 Answers 6
I have the same problem. My CPU % went back down to normal after I removed all my volumes.
I also manually removed some named volumes:
That doesn’t solve the overall issue of not being able to use volumes with Docker for mac. Right now I’m just being careful about the amount of volumes I use and closing Docker desktop when not in use.
My suspicion is that the issue is IO related. With MacOS volumes, this involves osxfs where there is some performance tuning you can perform. Mainly, if you can accept fewer consistency checks, you can set the volume mode to delegated for faster performance. See the docs for more details: https://docs.docker.com/docker-for-mac/osxfs-caching/. However, if your image contains a large number of small files, performance will suffer, especially if you also have lots of image layers.
You can also try the following command to debug any process issues within the embedded VM that docker uses:
To track down if it’s IO, you can also try the following:
That will run inside the alpine container running in the VM pid namespace, showing any IO happening from any process, whether or not that process is inside of a container. The stats are every 5 seconds for one minute (12 times) and then it will give you an average table per process. You can then -d to destroy the alpine container.
From the comments and edits, these stats may check out. A 4 core MBP has 8 threads, so full CPU utilization should be 800% if MacOS is reporting the same as other Unix based systems. Inside the VM there’s over 100% load shown in the top command for the average in the past minute (though less from the 5 and 15 averages) which is roughly what you see for the hyperkit process on the host. The instantaneous usage is over 12% from top, not 3%, since you need to add the system and user percentages. And the IO numbers shown in pidstat align roughly with what you see written to the qcow2 image.
Источник