Docker and virtualbox windows 10

Who Should Read This

If you’re running an older version of Windows, earlier than Windows 10, stop reading now. This article isn’t for you. If you’re on Windows 10 and trying to use Docker and VirtualBox side by side, read on.

This article explains how to Install Docker Toolbox on Windows 10 and how to overcome and troubleshoot the common pitfalls.

Preamble

Installing Docker on Windows 10 is a cinch unless you want to use it alongside VirtualBox.

Modern versions of Docker on Windows 10 use Windows Hyper-V, see https://docs.microsoft.com/en-us/virtualization/hyper-v-on-windows/about/, which is great except that Hyper-V doesn’t play well with VirtualBox (https://www.virtualbox.org/), and trying to install both on Windows 10 is likely to break VirtualBox.

Side note: It’s an issue which has been going on for a while. You can read the support ticket at https://www.virtualbox.org/ticket/16801. Recently some people have had success, but I didn’t when I last tried 6 months ago and I expect support to remain patchy.

A Real-Life Scenario

In my case, I have legacy projects, configured to spin up virtualized environments using Vagrant, with Bash and Puppet provisioners, which I need to keep on ice for clients who may come calling asking for updates or fixes. But, I also have other clients and projects using Docker, and I want to be able to switch from one to the other, hassle free.

The Solution — Docker Toolbox Rides to the Rescue

Docker Toolbox — https://docs.docker.com/toolbox/toolboxinstallwindows/ — is the legacy Windows desktop solution for Docker which doesn’t use Hyper-V being instead built on VirtualBox, and you’ve guessed it, the workaround most people use is to install Docker using this legacy option, rather than the newer version.

The problem is it’s not really meant for Windows 10 and so there are a few hiccoughs and the Docker QuickStart Terminal short-cut may not work. I list some of the more common issues and how to solve them below.

Side note: Alternatively you could use another Windows 10 computer; install a Linux partition and dual boot; try the Windows Linux Subsystem; install and uninstall Hyper-V as and when you need it; or try installing Docker inside a Linux VirtualBox machine.

Problem 1 – Are you running the wrong version of Virtual Box?

At the time of writing I downloaded v19.03.1 of Docker Toolbox from https://github.com/docker/toolbox/releases. This was released in July 2019 and supports Virtual Box 5.2.20. If you haven’t already installed VirtualBox it’ll be fine, you can install Docker Toolbox and the recommended version of VirutalBox (5.2.20) at the same time.

If you’re already using VirtualBox like me, I have 6.0.14 installed, and want to keep using the same (presumably newer) version then you’ll need to run the customised version of the Docker Toolbox installer and unselect VirtualBox from the install.

Side note: I deselected the Windows GIT installation too as that was already installed as well.

Problem 2 – The Desktop Short Cuts Don’t Work?

After installation you may find the desktop short-cuts created by the installer don’t work.

This maybe because you chose not to install Git for Windows as part of the Toolbox installation, or because Git was not installed to the standard (path) location on your machine.

You can fix this by editing the short-cut and amending the Target to point to the correct location of your GIT bash executable: …\Git\bin\bash.exe.

Problem 3 – Docker says Virtualisation isn’t installed?

The short-cut link works but when Docker runs it’s start.sh file (using GIT bash) it fails with the message:

“This computer doesn’t have VT-X/AMD-v enabled. Enabling it in the BIOS is mandatory»

The solution is to specify the virtualbox-no-vtx-check option when creating the VirtualBox environment.

Do this by going to the folder where you installed Docker Toolbox and editing the start.sh file (be careful with line endings and carriage returns), go to line 69, amend "${DOCKER_MACHINE}" create -d virtualbox $PROXY_ENV "${VM}" to "${DOCKER_MACHINE}" create -d virtualbox --virtualbox-no-vtx-check $PROXY_ENV "${VM}".

See this Stack Exchange question for more information: https://superuser.com/questions/1443294/docker-toolbox-doesnt-have-vt-x-amd-v-even-if-it-is-enabled.

Problem 4 — The Network Connection Fails

Despite VirtualBox working on your machine happily for eons, all of a sudden, and somewhat suspiciously after installing Docker Toolbox, it’s may start having issues connecting to the network card.

You’ll the a message with text like:

Failed to open/create the internal network ‘HostInterfaceNetworking-VirtualBox Host-Only Ethernet Adapter’ (VERRINTNETFLTIFNOT_FOUND)

In this case the old IT support engineer fallback is your friend – reinstall the drivers. Go to Network Adapter settings (I right click the Windows icon, select Device Manager), expand Network Adapters, then select the VirtualBox network adapters and update the drivers for them using the Browse my Computer Driver Software option.

I know this is crazy but trust me it works.

For more information check this out: https://stackoverflow.com/questions/33725779/failed-to-open-create-the-internal-network-vagrant-on-windows10

Final Checks

Once the Docker Quick Start Terminal short-cut works and takes you to a command line run the docker run hello-world command to make sure everything works.

Closing Thoughts

Docker is becoming more and more prevalent.

If you’re lucky enough to have more than one development machine or a Windows\Linux dual boot system then you’ll be able get along by switching between environments like I did, but after a while it will probably grate enough for you to want to try and find a solution to make Docker and VirtualBox live side by side on Windows 10.

The good news is that it looks like VirtualBox are trying to solve this issue and will eventually release something which works and is stable when Hyper-V is installed. Then we can all use the latest Docker installation for Windows 10, based on Hyper-V, and get on with our lives.

In the meantime I recommend the solution and workarounds outlined above.

Want to Thank Me?

Did you like the article? Was it helpful? If so why not buy me a coffee using Paypal? Buy me a coffee at https://www.paypal.me/justaguycoding

imageДанная публикация является разбором особенностей контейнерной виртуализации Docker под системой Windows.

Она не претендует на роль исчерпывающей и по мере необходимости будет обновляться и дополняться.

За практическим руководством с нуля советую обратиться к этой публикации.

Содержание

  • Предварительные настройки
  • Выбор между Docker Toolbox on Windows или Docker for Windows
  • Windows контейнеры и Linux контейнеры
  • Особенности монтирования папок
  • Монтирование с хост-машины или volume
  • Особенности разметки диска GPT и MBR
  • Docker Toobox to Windows
  • Docker Swarm
  • Проблемы с кодировкой
  • Полезные ссылки
  • Заключение

Предварительные настройки

Контейнерная виртуализация или виртуализация на уровне операционной системы Docker нативно работает только на дистрибутивах Linux и FreeBSD (экспериментально).
На Windows вам понадобится гостевая Linux система либо специальная минималистичная виртуальная машина с ядром Linux от разработчиков Docker, которая и ставится из коробки.
Само собой разумеется, что вы включили виртуализацию у себя в BIOS/UEFI
Пункт настройки может называться по-разному: VT-x, VT-d, Intel VT, AMD-V, Virtualization Technology.

Еще одним минимальным системным требованием будет разрядность системы x64 и версия не ниже Windows 7 Pro.

Выбор между Docker Toolbox on Windows или Docker for Windows

Появление Docker Toolbox on Windows и Docker Toolbox on Mac было большим событием.

Сборка включается в себя сам docker, утилиту docker-compose, утилиту для работы с виртуальной машиной docker-machine и клиент Kitematic.

Используется виртуальная машина (по умолчанию на VirtualBox) с минималистичным Linux окружением.

Позже для новых операционных систем выпустили Docker for Windows и Docker for Mac, которая на текущий момент является актуальной версией и продолжает развиваться.

Выбор между версиями не сложный:
— Если у вас Windows 10 x64 Pro, Enterprise или Education то включаем службу Hyper-V и ставим Docker for Windows.

Заметьте, что после включения службы Hyper-V пропадет возможность запускать и создавать x64 виртуальные машины на VirtualBox.

— Если же у вас другая версия Windows(7 Pro, 8, 8.1, 10 Home) то ставим VirtualBox и Docker Toolbox on Windows.

Несмотря на то, что Docker Toolbox разработчиками признан устаревшим работа с ним слабо отличается от Docker for Windows.

Вместе с установкой Docker Toolbox будет создана виртуальная машина.
В самом VirtualBox можно будет добавить оперативной памяти и ядер процессора на ваше усмотрение.

Windows контейнеры и Linux контейнеры

Docker for Windows предоставляет возможность переключать контейнеризацию между Linux и Windows версией.

В режиме Windows контейнеризации вы можете запускать только Windows приложения.
Замечу, что на май 2018 года в официальном Docker Hub существует всего 13 образов для Windows.

После включения Windows контейнеризации не забудьте добавить внешнюю сеть.

В конфигурационном файле docker-compose.yml это выглядит так:

networks:
  default:
    external:
      name: nat

Особенности монтирования папок

На примонтированных volume-ах не кидаются события файловой системы, поэтому inotify-tools не работает.
Спасибо пользователю eee

Если вы разрабатываете свой проект и пользуетесь docker-compose вне домашней папки то вам нужно будет проделать некоторые манипуляции.

Используя Docker for Windows для монтирования нового диска у вашего локального пользователя обязательно должен стоять пароль, который будет использоваться для доступа к shared папки.

Особенность заключается в том, что монтируемые внутрь контейнера диск будет монтироваться как от удаленной машины //10.0.75.1/DISK_DRIVE по протоколу SMB.

Для Docker Toolbox диски монтируются в самом VirtualBox на вкладке «Общие папки»
Пример для диска «D»:

Права доступа к монтируемым файлам и папкам

Как бы вам не хотелось, но для всех примонтированных из хост-машины файлов и папок будут стоять права 755 (rwx r-x r-x) и поменять их вы не сможете.

Остро встает вопрос при монтировании внутрь файла закрытого SSH ключа, права на который должны быть только у владельца(например 600).

В данном случае либо генерируют ключ при создании образа, либо прокидывают сокет ssh-agent с хост-машины.

Монтирование с хост-машины или volume

Монтирование внутрь контейнера происходит с использованием сети и протокола SMB, следовательно, внутри контейнера диск «D:\» будет примонтирован из источника //10.0.75.1/D
Использование volume внутри контейнера отображается как монтирование локального диска /dev/sda1, что влияет на скорость работы.

Простым тестом копирование файла на обычном HDD скорость работы получилась следующая:

Такая разница в скорости скорее всего связана с тем, что в volume данные сбрасываются на диск постепенно, задействуя кеш в ОЗУ.

Особенности разметки диска GPT и MBR

Данный пункт не является истинной так как опровергающей или подтверждающей информации в интернете найти не смог.

Если на хост-машине таблица разделов MBR, то контейнер с MySQL/MariaDB может упасть с ошибкой:

InnoDB: File ./ib_logfile101: ‘aio write’ returned OS error 122. Cannot continue operation

По умолчанию в базе данных включеён параметр innodb_use_native_aio, отвечающий за асинхронный ввод/вывод и его надо будет выключить.

Данная проблема также встречается на некоторых версиях MacOS.

Docker Toobox to Windows

Главное правило: начинать работу с запуска ярлыка на рабочем столе «Docker Quickstart Terminal», это решает 80% проблем.

— Бывает возникают проблемы с отсутствия переменных окружения, решается командой:

eval $(docker-machine env default)

— Если все же возникают проблемы из разряда «docker: error during connect», необходимо выполнить:

docker-machine env --shell cmd default 
@FOR /f "tokens=*" %i IN ('docker-machine env --shell cmd default') DO @%i

Название Docker Machine по умолчанию default.

Docker Swarm

Ни в Docker for Mac, ни в Docker for Windows — нет возможности использовать запущенные демоны в качестве клиентов кластера (swarm members).
Спасибо пользователю stychos

Проблемы с кодировкой

Используя Docker Toolbox(на Docker for Windows не удалось воспроизвести) нашлась проблема с тем, что русские комментарии в docker-compose.yml файле приводили к ошибке:

Traceback (most recent call last):
  File "docker-compose", line 6, in <module>
  File "compose\cli\main.py", line 71, in main
  File "compose\cli\main.py", line 124, in perform_command
  File "compose\cli\command.py", line 41, in project_from_options
  File "compose\cli\command.py", line 109, in get_project
  File "compose\config\config.py", line 283, in find
  File "compose\config\config.py", line 283, in <listcomp>
  File "compose\config\config.py", line 183, in from_filename
  File "compose\config\config.py", line 1434, in load_yaml
  File "site-packages\yaml\__init__.py", line 94, in safe_load
  File "site-packages\yaml\__init__.py", line 70, in load
  File "site-packages\yaml\loader.py", line 24, in __init__
  File "site-packages\yaml\reader.py", line 85, in __init__
  File "site-packages\yaml\reader.py", line 124, in determine_encoding
  File "site-packages\yaml\reader.py", line 178, in update_raw
  File "c:\projects\compose\venv\lib\encodings\cp1251.py", line 23, in decode
UnicodeDecodeError: 'charmap' codec can't decode byte 0x98 in position 1702: character maps to <undefined>
[4176] Failed to execute script docker-compose

Полезные ссылки

Docker Toolbox on Windows
Docker for Windows
Практическое руководство по Docker

Заключение

Особенности работы с Docker контейнеризацией на системе Windows не отличается от работы на Linux за исключение разобранных выше.

В статье я умышленно не упомянул заметно низкую скорость работы контейнеров и overhead используя систему Windows как само собой разумеющееся.

Буду рад услышать ваши отзывы. Не стесняйтесь предлагать улучшения или указывать на мои ошибки.

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

Какой версией Docker вы пользуетесь?


32.47%
Docker Toolbox on Windows
88


67.53%
Docker for Windows
183

Проголосовал 271 пользователь.

Воздержался 191 пользователь.

I’m usually using Ubuntu for development with Docker and VirtualBox, but I’ve recently started using Windows 10. Docker and VirtualBox can’t be used at the same time if Hyper-V is used.

Hyper-V runs Windows virtualized, so other virtualization software can’t be used at the same time. This is how and why I switched to docker-machine instead so I could run docker and VirtualBox at the same time.

Uninstall Docker and disable Hyper-V (if installed)

If you have Docker installed, then you need to remove it.

Then disable Hyper-V by pressing the Windows key and search for Turn Windows features on or off. Remove the checkbox on Hyper-V if it’s enabled.

Open an elevated shell by pressing the windows button and search for PowerShell. Right-click it and runs it as administrator.

Run the following command:
bcdedit /set hypervisorlaunchtype off

Then reboot.

Make sure Intel VT-x or AMD SVM is enabled

Press CTRL + ALT + DELETE and then Task Manager. Check if it says virtualization enabled as shown below.

How task manager looks if virtualization is enabled.

It should say enabled if VT-X or AMD SVM is enabled.

If it’s not enabled then you need to enable it in your BIOS.

Install VirtualBox

You can download VirtualBox from the official site and install it.

Install Docker Toolbox

We’re going to use Docker Toolbox to run docker in virtualbox.

The official guide found here has some issues, at least on AMD hardware. It keeps complaining about virtualization not being enabled when it is, so we need to make a small modification to disable the virtualization check.

  1. Download Docker Toolbox from GitHub.
  2. Run the install file you just downloaded.
  3. Open Notepad as administrator and open the file C:\Program Files\Docker Toolbox\start.sh. Make sure you select “all files” if you can’t find it.
  4. Find the line "${DOCKER_MACHINE}" create -d virtualbox $PROXY_ENV "${VM}" and replace it with "${DOCKER_MACHINE}" create -d virtualbox --virtualbox-no-vtx-check $PROXY_ENV "${VM}".
  5. Save the changes.
  6. Start Docker Quickstart Terminal.

Docker should now be working, and you can continue following the official guide from step 3.

Have fun with Docker and VirtualBox at the same time, and a faster Windows experience as Windows no longer runs virtualized 😊



  • Tags



    docker, hyper-v, virtualbox, virtualization

Oracle‘s VirtualBox is a hypervisor application, that is an application capable of running Virtual Machines. VirtualBox is freely available as Open Source Software under the terms of the GNU General Public License (GPL) version 2 and can be downloaded from its host web site. To install it in MS Windows just download the installer, execute it, and follow the instructions.

Docker is an application that performs operating-system-level virtualization, also known as “containerization“. Docker runs on Linux, Windows and macOS.

There are two ways to install Docker and run Docker containers on Windows:

  1. Enable virtualization in BIOS and Hyper-V in Windows features and then install Docker Desktop for Windows
  2. Install VirtualBox and then install Docker Toolbox. We are going to use this way.

Regardless of the way you choose to install Docker in a Windows machine, you need to enable Windows Sybsystem for Linux. Windows Subsystem for Linux, or WSL for brevity, is a compatibility layer for running Linux binary executables natively on Windows 10. More information may be found in Microsoft’s documentation.

In order to enable WSL on Windows 10 you have to go to Control Panel | Programs and Features | Turn Windows features on or off.

After that you may install VirtualBox and then install Docker ToolBox.

Docker ToolBox installer presents a dialog with installation options. Just uncheck the VirtualBox entry, since we already have it installed. Also you may already have git installed, so you may want to uncheck this option too.

After the installation of Docker ToolBox completes you may go to Start | Search and look for Docker Quickstart Terminal. Click on it and you’re ready to go.

Here is the Docker Getting Started guide.

Tested on:

Windows 10 Pro

About Theo Bebekis

A programmer living in Thessaloniki, Greece

This entry was posted in Docker and tagged Docker, VirtualBox, Windows. Bookmark the permalink.

Install Docker for Windows

Windows users use Docker Toolbox to install Docker software. Docker Toolbox includes the following Docker tools:

  • Docker CLI client for running Docker Engine to create images and containers
  • Docker Machine so you can run Docker Engine commands from Windows terminals
  • Docker Compose for running the docker-compose command
  • Kitematic, the Docker GUI
  • the Docker QuickStart shell preconfigured for a Docker command-line environment
  • Oracle VM VirtualBox

Because the Docker Engine daemon uses Linux-specific kernel features, you can’t
run Docker Engine natively in Windows. Instead, you must use the Docker Machine
command, docker-machine, to create and attach to a small Linux VM on your
machine. This VM hosts Docker Engine for you on your Windows system.

Step 1: Check your version

To run Docker, your machine must have a 64-bit operating system running Windows 7 or higher. Additionally, you must make sure that virtualization is enabled on your machine.
To verify your machine meets these requirements, do the following:

  1. Right click the windows message and choose System.

    If you aren’t using a supported version, you could consider upgrading your
    operating system.

    If you have a newer system, specifically 64bit Windows 10 Pro, with Enterprise and Education (1511 November update, Build 10586 or later), consider using Docker for Windows instead. It runs natively on the Windows, so there is no need for a pre-configured Docker QuickStart shell. It also uses Hyper-V for virtualization, so the instructions below for checking virtualization will be out of date for newer Windows systems. Full install prerequisites are provided in the Docker for Windows topic in What to know before you install.

  2. Make sure your Windows system supports Hardware Virtualization Technology and that virtualization is enabled.

    For Windows 8 or 8.1

    Choose Start > Task Manager and navigate to the Performance tab.
    Under CPU you should see the following:

    Release page

    If virtualization is not enabled on your system, follow the manufacturer’s instructions for enabling it.

    For Windows 7

  3. Verify your Windows OS is 64-bit (x64)

    How you do this verification depends on your Windows version. For details, see the Windows
    article How to determine whether a computer is running a 32-bit version or 64-bit version
    of the Windows operating system.

In this section, you install the Docker Toolbox software and several “helper” applications. The installation adds the following software to your machine:

  • Docker Client for Windows
  • Docker Toolbox management tool and ISO
  • Oracle VM VirtualBox
  • Git MSYS-git UNIX tools

If you have a previous version of VirtualBox installed, do not reinstall it with the Docker Toolbox installer. When prompted, uncheck it.

If you have Virtual Box running, you must shut it down before running the
installer.

  1. Go to the Docker Toolbox page.

  2. Click the installer link to download.

  3. Install Docker Toolbox by double-clicking the installer.

    The installer launches the “Setup — Docker Toolbox” dialog.

    If Windows security dialog prompts you to allow the program to make a
    change, choose Yes. The system displays the Setup — Docker Toolbox for
    Windows
    wizard.

    Release page

  4. Press Next to accept all the defaults and then Install.

    Accept all the installer defaults. The installer takes a few minutes to install all the components:

  5. When notified by Windows Security the installer will make changes, make sure you allow the installer to make the necessary changes.

    When it completes, the installer reports it was successful:

    Success

  6. Uncheck “View Shortcuts in File Explorer” and press Finish.

Step 3: Verify your installation

The installer places Docker Toolbox and VirtualBox in your Applications folder.
In this step, you start Docker Toolbox and run a simple Docker command.

  1. On your Desktop, find the Docker Toolbox icon.

    Desktop

  2. Click the icon to launch a Docker Toolbox terminal.

    If the system displays a User Account Control prompt to allow VirtualBox to make changes to your computer. Choose Yes.

    The terminal does several things to set up Docker Toolbox for you. When it is done, the terminal displays the $ prompt.

    Desktop

    The terminal runs a special bash environment instead of the standard Windows command prompt. The bash environment is required by Docker.

  3. Make the terminal active by click your mouse next to the $ prompt.

    If you aren’t familiar with a terminal window, here are some quick tips.

    /Terminal shell

    The prompt is traditionally a $ dollar sign. You type commands into the
    command line which is the area after the prompt. Your cursor is indicated
    by a highlighted area or a | that appears in the command line. After
    typing a command, always press RETURN.

  4. Type the docker run hello-world command and press RETURN.

    The command does some work for you, if everything runs well, the command’s
    output looks like this:

     $ docker run hello-world
     Unable to find image 'hello-world:latest' locally
     Pulling repository hello-world
     91c95931e552: Download complete
     a8219747be10: Download complete
     Status: Downloaded newer image for hello-world:latest
     Hello from Docker.
     This message shows that your installation appears to be working correctly.
    
     To generate this message, Docker took the following steps:
      1. The Docker Engine CLI client contacted the Docker Engine daemon.
      2. The Docker Engine daemon pulled the "hello-world" image from the Docker Hub.
         (Assuming it was not already locally available.)
      3. The Docker Engine daemon created a new container from that image which runs the
         executable that produces the output you are currently reading.
      4. The Docker Engine daemon streamed that output to the Docker Engine CLI client, which sent it
         to your terminal.
    
     To try something more ambitious, you can run an Ubuntu container with:
      $ docker run -it ubuntu bash
    
     For more examples and ideas, visit:
      https://docs.docker.com/userguide/
    

Looking for troubleshooting help?

Typically, the above steps work out-of-the-box, but some scenarios can cause problems. If your docker run hello-world didn’t work and resulted in errors, check out Troubleshooting for quick fixes to common problems.

A Windows specific problem you might encounter has to do with the NDIS6 host network filter driver, which is known to cause issues on some Windows
versions. For Windows Vista systems and newer, VirtualBox installs NDIS6 driver by default. Issues can range from system slowdowns to networking problems for the virtual machine (VM). If you notice problems, re-run the Docker Toolbox installer, and select the option to install VirtualBox with the NDIS5 driver.

Removing Toolbox involves removing all the Docker components it includes.

A full uninstall also includes removing the local and remote machines you created with Docker Machine. In some cases, you might want to keep machines created with Docker Machine.

For example, if you plan to re-install Docker Machine as a part of Docker for Windows you can continue to manage those machines through Docker. Or, if you have remote machines on a cloud provider and you plan to manage them using the provider, you wouldn’t want to remove them. So the step to remove machines is described here as optional.

To uninstall Toolbox on Windows, do the following:

  1. List your machines.

    $ docker-machine ls
    NAME                ACTIVE   DRIVER       STATE     URL                        SWARM
    dev                 *        virtualbox   Running   tcp://192.168.99.100:2376
    my-docker-machine            virtualbox   Stopped
    default                      virtualbox   Stopped
    

  2. Optionally, remove each machine. For example:

    $ docker-machine rm my-docker-machine
    Successfully removed my-docker-machine
    

  3. Uninstall Docker Toolbox using Window’s standard process for uninstalling programs through the control panel.

    Note: This process does not remove the docker-install.exe file. You must delete that file yourself.

  • Docker add user to docker group windows
  • Docker compose volumes windows 10
  • Dock windows как в mac os для windows
  • Doc panel для windows 10
  • Doc opener скачать бесплатно windows 10