Как настроить Docker и Windows Subsystem for Linux (WSL): история о любви?
Вы когда-нибудь чувствовали себя прекрасной принцессой, которую злой волшебник превратил в лягушку? Как будто происходит что-то не то? У меня такое бывает. Я пользуюсь исключительно UNIX и боюсь закрыть уютную командную строку. Мой терминал — моя крепость. Но так как иногда мне все-таки приходится пользоваться Microsoft Windows, я узнал о некоторых трюках, которые помогают мне справиться с таким стрессом.
Для ежедневной работы в терминале я установил Windows Subsystem for Linux вместе с дистрибутивом Ubuntu. Кроме того у меня установлен Linuxbrew, который помогает мне с установкой приложений сторонних производителей. Такое сочетание функционирует просто отлично! У меня есть следующая ссылка ко «внешним» (хранящимся на Windows) данным: ln -s
/external /mnt/c/Users/DoomHammer. Почти все необходимое можно осуществить подобным образом. Но до тех пор, пока не нужно использовать Docker.
Что такого особенного в Docker?
В отличие от многих приложений, используемых мной ежедневно, Docker является системным. То есть он находится глубоко в системе и для его работы на хост-компьютере необходим демон. В данном случае под хост-компьютером я подразумеваю Microsoft Windows.
Значит ли это, что мы не можем использовать Docker изнутри WSL? Можем, но нужно постараться, чтобы добраться до него. Во-первых, нужно установить Docker под Windows. Для этого есть Docker Enterprise Editions для Windows Server 2016 (и новее), Community Edition для Windows 10 Professional и Enterprise. У меня установлена Windows 10 Home.
Docker на Windows 10 Home
Настройка Docker в Windows 10 Home кажется более сложной. Для Docker Community Edition необходима поддержка системы Hyper-V, которая недоступна для версии Home. То есть мне надо было найти Docker Toolbox — более раннюю версию на основе Docker Machine и Virtualbox. Но после установки Virtualbox выдал окно с ошибкой о том, что запустить виртуальную машину невозможно.
Как оказалось, в BIOS у меня была выключена функция виртуализации. Видимо для безопасности. После включения функции, я снова запускаю Virtualbox. Проблема осталась. В интернете посоветовали проверить systeminfo. Хорошо. Там показано, что работает какой-то гипервизор. Но ведь не Virtualbox или, тем более, Hyper-V, верно?
К моему удивлению, все это время работал именно Hyper-V. Похоже в версии Home нет инструментов для использования Hyper-V, но это не означает, что гипервизор не работает. К счастью, чтобы выключить его, нужно просто ввести в команду bcdedit /set hypervisorlaunchtype off. После перезагрузки Virtualbox заработал. Ура!
Docker и WSL — лучшие друзья навеки?
С работающим Virtualbox я открыл Docker Quickstart Terminal. Во время первого запуска он создает Docker Machine (вот зачем нужен Virtualbox) для функционирования в качестве хоста для всех контейнеров. Далее ввожу команду docker run —rm hello-world и наблюдаю за индикатором выполнения загрузки подходящего образа. Снова ура!
Теперь вместо cmd.exe я использую Docker в WSL. Как так получилось? К счастью, у WSL есть доступ к бинарным файлам Windows. То есть я могу ввести команду docker-machine.exe ls для того, чтобы увидеть машину, созданную Docker Toolbox. Она будет называться просто default. Если не указан статус «Running», то можно запустить машину с помощью команды docker-machine.exe start. Каждый раз при запуске Docker Machine помните, что в отличие от cmd.exe,выполнение ( .exe) является обязательным.
Чтобы указать переменные окружения, вызывается docker-machine.exe env.
К сожалению, они выводятся в формате для cmd.exe, а не Bourne shell (bash или zsh). Но мы можем изменить это с помощью docker-machine.exe env — shell sh.
Почти готово. Нужно сделать кое-что еще. Путь к сертификату написан как путь Windows. Как перевести это во что-то понятное для WSL? В WSL есть хорошая утилита wslpath , благодаря которой можно ввести команду export DOCKER_CERT_PATH=$(wslpath $DOCKER_CERT_PATH). Готово!
Но нам все еще нужны инструменты пользовательского пространства. Итак, с помощью диспетчера пакетов установите Docker Engine и Docker Compose. В моем случае нужно ввести команду brew install docker docker-compose. После нее вводим команду docker run —rm hello-world. На этом все, мои поздравления!
На этом все?
Конечно же нет. Как видим, bind-mount работает некорректно, потому что Docker-демон ожидает подходящего пути Windows, а пути WSL не переводятся автоматически. Но есть несколько приемов, которые помогут нам в данной ситуации.
Выбор конкретного метода зависит от вашей версии Windows. Нажмите Win+R и введите команду winver. Появится сообщение, в котором указана версия. Наример:
Если версия будет 18.03 или новее, то можно отредактировать /etc/wsl.conf следующим образом:
То есть WSL смонтирует диск С: под /c/ вместо обычного /mnt/c. Почему это важно? Потому что этого ожидает Docker-демон от путей Windows. Кстати, после сохранения файла необходимо перезайти (re-login), чтобы изменения вступили в силу.
Осторожно! Если вы используете WSL-терминал , то это изменение сломает его. Тогда можно сделать следующее.
Если вы не хотите перезагружать систему или версия Windows более ранняя, то можно примонтировать одну точку монтирования к другой следующим образом:
sudo mkdir /c
sudo mount —bind /mnt/c /c
Так быстрее, но функция будет доступна только до тех пор, пока вы не выйдете из системы. После перезапуска нужно повторять процедуру или добавить ее в конфигурацию среды выполнения shell (например,
/.zshrc). Это происходит из-за того, что /etc/fstab не работает на WSL так, как требуется.
Теперь можно запускать Docker с монтированием, но только если приложение находится в файловой системе WIndows. У вас не должно возникнуть проблем с командной строкой docker, которая ожидает абсолютные пути, но с Docker Compose нужно быть максимально внимательным. Он позволяет использовать относительные пути, и все, что начинается с ./ не будет работать.
Если вы все-таки решили монтировать файловую систему WSL с помощью Docker, то можете попробовать заменить все ./ и $PWD на /c/Users/$USERNAME/AppData/Local/lxss. Здесь $USERNAMEозначает не имя пользователя WSL, а имя пользователя Windows.
Я также хотел написать оболочку для Docker Compose, чтобы изменить рабочий каталог на lxss, но у WSL нет к нему доступа. И думаю, это правильно!
И последнее
Мы можем запускать Docker и связывать каталоги данных. Что еще нам нужно? Может рабочая переадресация портов? В отличие от Native solutions, ипользуя Docker через Docker Machine, необходимо вызывать все службы через $(docker-machine ip):$PORT вместо обычного localhost:$PORT. Существует способ обойти все это, хотя и не очень элегантный:
Думаю, можно написать оболочку для Docker, чтобы выполнять все эти манипуляции при каждом запуске нового контейнера. Но я лично еще не проверял данный метод, потому что мне достаточно переадресации одного порта.
Надеюсь, данные советы облегчат работу с Docker на WSL. Лично мне они очень помогли.
Install Docker Desktop on Windows
Docker Desktop for Windows is the Community version of Docker for Microsoft Windows. You can download Docker Desktop for Windows from Docker Hub.
This page contains information on installing Docker Desktop on Windows 10 Pro, Enterprise, and Education. If you are looking for information about installing Docker Desktop on Windows 10 Home, see Install Docker Desktop on Windows Home.
By downloading Docker Desktop, you agree to the terms of the Docker Software End User License Agreement and the Docker Data Processing Agreement.
What to know before you install
System Requirements
Windows 10 64-bit: Pro, Enterprise, or Education (Build 16299 or later).
The following hardware prerequisites are required to successfully run Client Hyper-V on Windows 10:
- 64 bit processor with Second Level Address Translation (SLAT)
- 4GB system RAM
- BIOS-level hardware virtualization support must be enabled in the BIOS settings. For more information, see Virtualization.
Note: Docker supports Docker Desktop on Windows based on Microsoft’s support lifecycle for Windows 10 operating system. For more information, see the Windows lifecycle fact sheet.
What’s included in the installer
The Docker Desktop installation includes Docker Engine, Docker CLI client, Docker Compose, Notary, Kubernetes, and Credential Helper.
Containers and images created with Docker Desktop are shared between all user accounts on machines where it is installed. This is because all Windows accounts use the same VM to build and run containers. Note that it is not possible to share containers and images between user accounts when using the Docker Desktop WSL 2 backend.
Nested virtualization scenarios, such as running Docker Desktop on a VMWare or Parallels instance might work, but there are no guarantees. For more information, see Running Docker Desktop in nested virtualization scenarios.
About Windows containers
Looking for information on using Windows containers?
- Switch between Windows and Linux containers describes how you can toggle between Linux and Windows containers in Docker Desktop and points you to the tutorial mentioned above.
- Getting Started with Windows Containers (Lab) provides a tutorial on how to set up and run Windows containers on Windows 10, Windows Server 2016 and Windows Server 2019. It shows you how to use a MusicStore application with Windows containers.
- Docker Container Platform for Windows articles and blog posts on the Docker website.
Install Docker Desktop on Windows
Double-click Docker Desktop Installer.exe to run the installer.
If you haven’t already downloaded the installer ( Docker Desktop Installer.exe ), you can get it from Docker Hub. It typically downloads to your Downloads folder, or you can run it from the recent downloads bar at the bottom of your web browser.
When prompted, ensure the Enable Hyper-V Windows Features option is selected on the Configuration page.
Follow the instructions on the installation wizard to authorize the installer and proceed with the install.
When the installation is successful, click Close to complete the installation process.
If your admin account is different to your user account, you must add the user to the docker-users group. RunВ Computer ManagementВ as an administrator and navigate toВ Local Users and Groups > GroupsВ >В docker-users.В Right-click to add the user to the group. Log out and log back in for the changes to take effect.
Start Docker Desktop
Docker Desktop does not start automatically after installation. To start Docker Desktop, search for Docker, and select Docker Desktop in the search results.
When the whale icon in the status bar stays steady, Docker Desktop is up-and-running, and is accessible from any terminal window.
If the whale icon is hidden in the Notifications area, click the up arrow on the taskbar to show it. To learn more, see Docker Settings.
When the initialization is complete, Docker Desktop launches the onboarding tutorial. The tutorial includes a simple exercise to build an example Docker image, run it as a container, push and save the image to Docker Hub.
Congratulations! You are now successfully running Docker Desktop on Windows.
If you would like to rerun the tutorial, go to the Docker Desktop menu and select Learn.
Uninstall Docker Desktop
To uninstall Docker Desktop from your Windows machine:
- From the Windows Start menu, select Settings >Apps >Apps & features.
- Select Docker Desktop from the Apps & features list and then select Uninstall.
- Click Uninstall to confirm your selection.
Note: Uninstalling Docker Desktop will destroy Docker containers and images local to the machine and remove the files generated by the application.
Switch between Stable and Edge versions
Docker Desktop allows you to switch between Stable and Edge releases. However, you can only have one version of Docker Desktop installed at a time. Switching between Stable and Edge versions can destabilize your development environment, particularly in cases where you switch from a newer (Edge) channel to an older (Stable) channel.
For example, containers created with a newer Edge version of Docker Desktop may not work after you switch back to Stable because they may have been created using Edge features that aren’t in Stable yet. Keep this in mind as you create and work with Edge containers, perhaps in the spirit of a playground space where you are prepared to troubleshoot or start over.
Experimental features are turned on by default on Edge releases. However, when you switch from a Stable to an Edge release, you must turn on the experimental features flag to access experimental features. From the Docker Desktop menu, click Settings > Command Line and then turn on the Enable experimental features toggle. Click Apply & Restart for the changes to take effect.
To safely switch between Edge and Stable versions, ensure you save images and export the containers you need, then uninstall the current version before installing another. For more information, see the section Save and Restore data below.
Save and restore data
You can use the following procedure to save and restore images and container data. For example, if you want to switch between Edge and Stable, or to reset your VM disk:
Use docker save -o images.tar image1 [image2 . ] to save any images you want to keep. See save in the Docker Engine command line reference.
Use docker export -o myContainner1.tar container1 to export containers you want to keep. See export in the Docker Engine command line reference.
Uninstall the current version of Docker Desktop and install a different version (Stable or Edge), or reset your VM disk.
Use docker load -i images.tar to reload previously saved images. See load in the Docker Engine.
Use docker import -i myContainer1.tar to create a file system image corresponding to the previously exported containers. See import in the Docker Engine.
For information on how to back up and restore data volumes, see Backup, restore, or migrate data volumes.