Время на прочтение5 мин
Количество просмотров5.2K
Всем привет! Меня зовут Андрей, и я работаю DevOps инженером в компании Exness в команде разработки. Моя основная деятельность связана со сборкой, деплоем и поддержкой приложений в docker под операционной системой Linux (далее — ОС). Не так давно у меня появилась задача с теми же активностями, но в качестве целевой ОС проекта стала Windows Server и набор проектов на C++. Для меня это было первое плотное взаимодействие c docker контейнерами под ОС Windows и в целом с приложениями на C++. Благодаря этому я получил интересный опыт и узнал о некоторых тонкостях контейнеризации приложений в ОС Windows.
В этой статье хочу рассказать, с какими трудностями мне пришлось столкнуться, каким образом их удалось решить. Надеюсь, это окажется полезным для решения ваших текущих и будущих задач. Приятного чтения!
Почему контейнеры?
В компании есть существующая инфраструктура оркестратора контейнеров Hashicorp Nomad и связанных компонентов — Consul и Vault. Поэтому контейнеризация приложений была выбрана как унифицированный метод доставки готового решения. Так как в инфраструктуре проекта имеются docker-хосты с версиями ОС Windows Server Core 1803 и 1809, то необходимо собирать отдельно версии docker-образов для 1803 и 1809. В версии 1803 важно помнить о том, что номер ревизии сборочного docker-хоста должен совпадать с номером ревизии базового docker-образа и хоста, где контейнер из этого образа будет запущен. Версия 1809 лишена такого недостатка. Подробнее можно прочитать здесь.
Почему multi-stage?
У инженеров команд разработки доступ к сборочным хостам отсутствует или сильно ограничен, нет возможности оперативно управлять набором компонентов для сборки приложения на этих хостах, например, установить дополнительный toolset или workload для Visual Studio. Поэтому мы приняли решение — все необходимые для сборки приложения компоненты установить в сборочный docker-образ. При необходимости можно достаточно быстро изменить только dockerfile и запустить пайплайн создания этого образа.
От теории к делу
В идеальной docker multi-stage сборке образа подготовка окружения для сборки приложения происходит в том же dockerfile скрипте, что и сборка самого приложения. Но в нашем случае было добавлено промежуточное звено, а именно, шаг предварительного создания docker-образа со всем необходимым для сборки приложения. Так сделано, потому что хотелось использовать возможность docker cache, чтобы сократить время установки всех зависимостей.
Давайте разберем основные моменты dockerfile скрипта для формирования этого образа.
Для создания образов разных версий ОС в dockerfile можно определить аргумент, через который при сборке передаётся номер версии, и он же тэг базового образа.
Полный список тэгов образов Microsoft Windows Server можно найти здесь.
ARG WINDOWS_OS_VERSION=1809
FROM mcr.microsoft.com/windows/servercore:$WINDOWS_OS_VERSION
По умолчанию команды в инструкции RUN внутри dockerfile в ОС Windows выполняются в консоли cmd.exe. Для удобства написания скриптов и расширения функционала используемых команд переопределим консоль исполнения команд на Powershell через инструкцию SHELL.
SHELL ["powershell", "-Command", "$ErrorActionPreference = 'Stop';"]
Следующим шагом устанавливаем пакетный менеджер chocolatey и необходимые пакеты:
COPY chocolatey.pkg.config .
RUN Set-ExecutionPolicy Bypass -Scope Process -Force ;\
[System.Net.ServicePointManager]::SecurityProtocol = \
[System.Net.ServicePointManager]::SecurityProtocol -bor 3072 ;\
$env:chocolateyUseWindowsCompression = 'true' ;\
iex ((New-Object System.Net.WebClient).DownloadString( \
'https://chocolatey.org/install.ps1')) ;\
choco install chocolatey.pkg.config -y --ignore-detected-reboot ;\
if ( @(0, 1605, 1614, 1641, 3010) -contains $LASTEXITCODE ) { \
refreshenv; } else { exit $LASTEXITCODE; } ;\
Remove-Item 'chocolatey.pkg.config'
Чтобы установить пакеты, используя chocolatey, можно просто передать их списком или же установить по одному в том случае, если необходимо передать уникальные параметры для каждого пакета. В нашей ситуации мы использовали манифест файл в формате XML, в котором указан список необходимых пакетов и их параметров. Его содержимое выглядит так:
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="python" version="3.8.2"/>
<package id="nuget.commandline" version="5.5.1"/>
<package id="git" version="2.26.2"/>
</packages>
Далее мы устанавливаем среду сборки приложения, а именно, MS Build Tools 2019 — это облегченная версия Visual Studio 2019, которая содержит в себе минимально необходимый набор компонентов для компиляции кода.
Для полноценной работы с нашим C++ проектом нам потребуются дополнительные компоненты, а именно:
- Workload C++ tools
- Toolset v141
- Windows 10 SDK (10.0.17134.0)
Установить расширенный набор инструментов в автоматическом режиме можно при помощи файла конфигурации в формате JSON. Содержимое файла конфигурации:
Полный список доступных компонентов можно найти на сайте документации Microsoft Visual Studio.
{
"version": "1.0",
"components": [
"Microsoft.Component.MSBuild",
"Microsoft.VisualStudio.Workload.VCTools;includeRecommended",
"Microsoft.VisualStudio.Component.VC.v141.x86.x64",
"Microsoft.VisualStudio.Component.Windows10SDK.17134"
]
}
В dockerfile выполняется скрипт установки, и для удобства добавляется путь к исполняемым файлам build tools в переменную окружения PATH. Также желательно удалить ненужные файлы и директории, чтобы уменьшить размер образа.
COPY buildtools.config.json .
RUN Invoke-WebRequest 'https://aka.ms/vs/16/release/vs_BuildTools.exe' \
-OutFile '.\vs_buildtools.exe' -UseBasicParsing ;\
Start-Process -FilePath '.\vs_buildtools.exe' -Wait -ArgumentList \
'--quiet --norestart --nocache --config C:\buildtools.config.json' ;\
Remove-Item '.\vs_buildtools.exe' ;\
Remove-Item '.\buildtools.config.json' ;\
Remove-Item -Force -Recurse \
'C:\Program Files (x86)\Microsoft Visual Studio\Installer' ;\
$env:PATH = 'C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\MSBuild\Current\Bin;' + $env:PATH; \
[Environment]::SetEnvironmentVariable('PATH', $env:PATH, \
[EnvironmentVariableTarget]::Machine)
На этом этапе наш образ для компиляции C++ приложения готов, и можно приступать непосредственно к созданию docker multi-stage сборке приложения.
Multi-stage в действии
В качестве сборочного образа будем использовать созданный образ со всем инструментарием на борту. Как и в предыдущем dockerfile скрипте, добавим возможность динамически указывать номер версии/ тэга образа для удобства переиспользования кода. Важно добавить метку as builder к сборочному образу в инструкции FROM.
ARG WINDOWS_OS_VERSION=1809
FROM buildtools:$WINDOWS_OS_VERSION as builder
Настал черед сборки приложения. Здесь все достаточно просто: скопировать исходный код и все, что с ним связано, и запустить процесс компиляции.
COPY myapp .
RUN nuget restore myapp.sln ;\
msbuild myapp.sln /t:myapp /p:Configuration=Release
Завершающий этап создания конечного образа — указание базового образа приложения, где будут располагаться все артефакты компиляции и файлы конфигурации. Для копирования скомпилированных файлов с промежуточного сборочного образа надо указать параметр --from=builder в инструкции COPY.
FROM mcr.microsoft.com/windows/servercore:$WINDOWS_OS_VERSION
COPY --from=builder C:/x64/Release/myapp/ ./
COPY ./configs ./
Теперь остается добавить необходимые зависимости для работы нашего приложения и указать команду запуска через инструкции ENTRYPOINT или CMD.
Заключение
В этой статье я рассказал, как создать полноценную среду компиляции C++ приложений внутри контейнера под Windows и о том, как использовать возможности docker multi-stage сборок для создания полноценных образов нашего приложения.
Are you new to Docker Windows Images? Are you currently working in a Windows shop and curious to learn about Docker builds for container images? You have come to the right place. The best way to learn about new something is by doing with the docker build and docker build "tag" commands!
Not a reader? Watch this related video tutorial!
Not seeing the video? Make sure your ad blocker is disabled.
In this article, you are going to learn how to create your first Windows Docker image from a Dockerfile using the docker build command.
Let’s get started!
Understanding Docker Container Images
For years, the only way to test or perform development on multiple operating systems (OS) was to have several dedicated physical or virtual machines imaged with the OS version of your choice. This methodology required more hardware and overhead to provision new machines for each software and OS specification.
However, these days the usage of Docker container images has grown partly due to the popularity of micro-service architecture. In response to the rise in Docker’s popularity, Microsoft has started to publicly support Docker images for several flagship products on their Docker Hub page. They have even added native support for images for Windows as a product feature in Windows 10 and Windows Server 2016!
A Docker image is run on a container by using the Docker Engine. Docker images have many benefits such as portability (applicable to multiple environments and platforms), customizable, and highly scalable. As you can see below, unlike traditional virtual machines, the Docker engine runs on a layer between the host OS kernel and the isolated application services that are being containerized.
Understanding Docker Build and Images
The docker build command can be leveraged to automate container image creation, adopt a container-as-code DevOps practice, and integrate containerization into the development cycle of your projects. Dockerfiles are simply text files that contain build instructions used by Docker to create a new container image that is based on an existing image.
The user can specify the base image and list of commands to be run when a container image is deployed or startup for the first time. In this article, you will learn how to create a Windows-based docker image from Dockerfile using a Windows container.
This process has several benefits over using a pre-built container image:
- You are able to rebuild a container image for several versions of Windows – which is great for testing code changes on several platforms.
- You will have more control over what is installed in the container. This will allow you to keep your container size to a minimum.
- For security reasons, you might want to check the container for vulnerabilities and apply security hardening to the base image
Prerequisites/Requirements
This article is a walkthrough on learning about learning how to build a Docker image using a Dockerfile. If you’d like to follow along, ensure that you have the following prerequisites in place.
- Docker for Windows installed. I’ll be using the Docker Community Edition (CE) version 2.1.0.4 in my environment.
- Internet access is needed for downloading the Docker images
- Windows 10+ Operating System (version 1709 is being used for this tutorial)
- Nested virtualization enabled
- 5 GB of free diskspace on your local machine
- PowerShell 5.0+
- This tutorial uses the Visual Studio Code IDE. However feel free to use what ever IDE you’d prefer.
Note: Be sure to enable Windows Containers Configuration when installing Docker.
Getting Prepared
You’ll first need a folder to store all of the Docker images and containers you’ll be building from those images. To do so, open a Powershell or cmd terminal (you’ll be using PowerShell throughout this article) and create a new directory called C:\Containers.
Once the folder is created, change to that directory. This puts the console’s current working directory to C:\Containers to default all downloads to this directory.
PS51> mkdir C:\Containers
PS51> cd C:\Containers
In this article, you’ll get a headstart. Most of the files to work through this project are already available. Once the folder is created, perform a Git pull to copy over the files needed for this article from the TechSnips Github repository to the C:\Containers folder. Once complete, check to make sure that the C:\Containers folder looks like below.
Downloading the IIS Windows Docker Image
The first task to perform is to download a “template” or base image. You’ll be building your own Docker image later but first, you need an image to get started with. You’ll be downloading the latest IIS and Windows Server Core Images that are required for this tutorial. The updated list of images can be found on the official Microsoft Docker hub image page.
Reviewing the Current Docker Base Images
Before downloading the image from the image repository, let’s first review the current Docker base images that you currently have on your local system. To do so, run a PowerShell console as Administrator and then type docker images. This command returns all images on your local system.
As you can see below, the images available are initially empty.
Downloading the Base Image
Now it’s time to download the base IIS image from Docker Hub. To do so, run docker pull as shown below. This process can take some time to complete depending on your internet speeds.
PS51> docker pull mcr.microsoft.com/windows/servercore/iis
Now run docker images and you should have the latest Microsoft Windows Core IIS image available for this tutorial.
Inspecting the Dockerfile
In an earlier step, you had downloaded an existing Dockerfile for this tutorial. Let’s now take a look at exactly what that entails.
Open the C:\Containers\Container1\Dockerfile file in your favorite editor. The contents of this Dockerfile are used to define how the container image will be configured at build time.
You can see an explanation of what each piece of this file does in the in-line comments.
# Specifies that the latest microsoft/iis image will be used as the base image
# Used to specify which base container image will be used by the build process.
# Notice that the naming convention is "**owner/application name : tag name**"
# (shown as microsoft/iis:latest); so in our case the owner of the image is
# Microsoft and the application is IIS with the "latest" tag name being used
# to specify that you will pull the most recent image version available.
FROM microsoft/iis:latest
# Copies contents of the wwwroot folder to the inetpub/wwwroot folder in the new container image
# Used to specify that you want to copy the WWWroot folder to the IIS inetpub WWWroot
# folder in the container. You don't have to specify the full path to your local
# files because docker already has the logic built-in to reference files and folders
# relative to the docker file location on your system. Also, make note that that
# docker will only recognize forward slashes for file paths - since this is a
# Windows based container instead of Linux.
COPY wwwroot c:/inetpub/wwwroot
# Run some PowerShell commands within the new container to set up the image
# Run the PowerShell commands to remove the default IIS files and create a new
# application pool called TestPool
RUN powershell Remove-Item c:/inetpub/wwwroot/iisstart.htm -force
RUN powershell Remove-Item c:/inetpub/wwwroot/iisstart.png -force
RUN powershell Import-Module WebAdministration
RUN powershell New-WebAppPool -Name 'TestPool'
# Exposes port 80 on the new container image
# Used to open TCP port 80 for allowing an http connection to the website.
# However, this line is commented out, because the IIS container has this port
# already open by default.
#EXPOSE 80
# Sets the main command of the container image
# This tells the image to run a service monitor for the w3svc service.
# When this is specified the container will automatically stop running
# if the w3svc service stopped. This line is commented out because of the
# IIS container already has this entrypoint in place by default.
#ENTRYPOINT ["C:\\ServiceMonitor.exe", "w3svc"]
Building a New Docker Image
You’ve got the Dockerfile ready to go and a base IIS image downloaded. Now it’s time to build your new Docker image using the Dockerfile.
To build a new image, use the docker build "tag" command. This command creates the image. For this article, you can see below you’re also using the -t ** option which replaces the “tag” portion. This option allows you to give your new image a friendly tag name and also reference the Dockerfile by specifying the folder path where it resides.
Below you can see an example of ensuring the console is in the C:\Containers directory and then building a new image from the Dockerfile in the C:\Containers\Container1 directory.
PS51> cd C:\Containers
PS51> docker build -t container1 .\Container1
Once started, you can see the progress of the command as it traverses each instruction in the docker file line by line:
Once done, you should now have a new Docker image!
Now run the docker images command to view the images that are available. You can see below an example of the container1 image created.
Note: The
docker build —helpcommand is a useful parameter to display detailed information on the docker command being run.
Running the Docker Container
At this point, you should have a new image created. It’s time to spin up a container using that image. To bring up a new container, use the docker run command.
The docker run command will bring up a new Docker container based on the container1 image that you created earlier. You can see an example of this below.
Notice that the -d parameter is used. This tells the docker runtime to start the image in the detached mode and then exit when the root process used to run the container exits.
When docker run completes, it returns the ID of the container created. The example below is capturing this ID into a $containerID variable so we can easily reference it later.
PS51> $containerID = docker run -d container1
PS51> $containerID
Once the container is brought up, now run the docker ps command. This command allows you to see which containers are currently running using each image. Notice below that the running image is automatically generated a nickname (busy_habit in this case). This nickname is sometimes used instead of the container ID to manage the container.
Running Code Inside a Docker Container
A new container is built from a new image you just created. Let’s now start actually using that container to run code. Running code inside of a Docker container is done using the docker exec command.
In this example, run docker exec to view PowerShell output for the Get-ChildItem command in the container using the command syntax below. This will ensure the instructions in the Dockerfile to remove the default IIS files succeeded.
PS51> docker exec $containerID powershell Get-ChildItem c:\inetpub\wwwroot
You can see below that the only file that exists is index.html which means the default files were removed.
Now run the ipconfig command in the container to get the local IP address of the container image so that you can try to connect to the IIS website.
PS51> docker exec $containerID ipconfig
You can see below that ipconfig was run in the container just as if running on your local computer and has return all of the IP information.
ipconfig in a Docker containerInspecting the IIS Website
Now it’s time to reveal the fruits of your labor! It’s time to see if the IIS server running in the Docker container is properly serving up the index.html page.
Open a browser and paste the IP4 Address found via ipconfig into the address bar. If all is well, you should see a Hello World!! message like below.
Reviewing Docker History
One useful command to use when working with Docker containers i the docker history command. Although not necessarily related to creating an image or container itself, the docker history command is a useful command that allows you to review changes made to the container image.
PS51> docker history container1
You can see below, that docker history returns all of the Dockerfile and PowerShell activity performed on the container1 container you’ve been working with.
docker historyCleaning up the Running Docker Images
The steps below are used to cleanup all stopped containers running on your machine. This will free up diskspace and system resources.
Run the docker ps command to view a list of the containers running on your system:
Now stop the running containers using the docker stop command:
PS51> docker stop <image nick name: busy_haibt in my case>
PS51> docker stop <image nick name: unruffled_driscoll in my case>
Finally you can permanently remove the stopped containers using the docker system prune command.
PS51> docker system prune
Further Reading
- Creating Your First Docker Windows Server Container
- How to Manage Docker Volumes on Windows
-
Dockerizing MCP – Bringing Discovery, Simplicity, and Trust to the Ecosystem
Discover the Docker MCP Catalog and Toolkit, a new way to source, use, and scale with MCP tools.
Read now
-
Update on the Docker DX extension for VS Code
Learn about the latest changes to the Docker DX extension for VS Code, new features for authoring, and what’s coming next to enhance your container workflows.
Read now
-
Docker Desktop 4.41: Docker Model Runner supports Windows, Compose, and Testcontainers integrations, Docker Desktop on the Microsoft Store
Docker Desktop 4.41 brings new tools for AI devs and teams managing environments at scale — build faster and collaborate smarter.
Read now
-
How to build and deliver an MCP server for production
In December of 2024, we published a blog with Anthropic about their totally new spec (back then) to run tools with AI agents: the Model Context Protocol, or MCP. Since then, we’ve seen an explosion in developer appetite to build, share, and run their tools with Agentic AI – all using MCP. We’ve seen new…
Read now
In this tutorial, I will demonstrate how to host an ASP.NET Core 2.2 application on Windows Containers by using a Docker image. A Docker image will be packaged with an ASP.NET Core application that will be run when a container is spun up.
Before we get started with creating a Docker image. Let’s make sure we have prerequisites done.
Prerequisites
- Installing docker-cli and other components to get started
- Visual Studio code.
- Docker extension for visual studio code.
Once you have the prerequisites, we will use a publicly available ASP.NET Core base image from Microsoft. Microsoft maintains their Docker images on Docker hub. Docker hub is a container registry to manage your Docker images either by exposing the image publicly or maintaining it privately. Private image responsibilities cost money. Visit Docker Hub website to learn more about image repository management.
Step 1: Open the PowerShell console as an administrator
Step 2: Let’s get started by pulling ASP.NET Core 2.2 Docker image from Docker hub by executing the below command.
docker pull mcr.microsoft.com/dotnet/core/aspnet:2.2
Your output should look similar to what is shown below:
Step 3: Create a folder with your preference name whatever you prefer. I will use c:\docker\ for demonstration purposes.
Step 4: Download ASP.NET Core application package from this URL.
Invoke-WebRequest -UseBasicParsing -OutFile c:\docker\WebAppCore2.2.zip https://github.com/rahilmaknojia/WebAppCore2.2/archive/master.zip
What we are doing in the above command is downloading packaged code that is already built to save time on building a package.
Step 5: Extract WebAppCore2.2.zip by using the PowerShell 5.0 native command. If you do not have PowerShell 5.0 and above, you will have to manually extract the package.
Expand-Archive c:\docker\WebAppCore2.2.zip -DestinationPath c:\docker\ -Force
Step 6: Now let’s create a Docker file in c:\docker folder.
New-Item -Path C:\docker\Dockerfile -ItemType File
Step 7: Go ahead and open C:\docker folder path in Visual Studio Code.
Step 8: Now we will open Dockerfile by double-clicking on the file in Visual Studio Code to start writing the required steps to build an image.
Copy and paste the code below into Dockerfile.
# Pull base image from Docker hub
FROM mcr.microsoft.com/dotnet/core/aspnet:2.2
# Create working directory
RUN mkdir C:\\app
# Set a working directory
WORKDIR c:\\app
# Copy package from your machine to the image. Also known as staging a package
COPY WebAppCore2.2-master/Package/* c:/app/
# Run the application
ENTRYPOINT ["dotnet", "WebAppCore2.2.dll"]
What we told the
Dockerfileis to pull an asp.net core base image from Docker hub. Then we ran a command to create a directory calledappinc:\apppath. We also told the container to setc:\appas a working directory. That way we can access binary directly when the container is spun up. We also added a step to copy all the binaries fromc:\docker\WebAppCore2.2-master\Package\to destination path in containerc:\app. Once we had the package staged in the container, we told it to run the application by executingdotnet WebAppCore2.2.dllso that the app would be accessible from outside the container. To learn more aboutDockerfilefor Windows, check out this Microsoft documentation.Now that you have the required steps to build an image, let’s go ahead with the below steps.
Step 9: Navigate to Dockerfile working directory from PowerShell console. If you are already in that path, you can ignore it.
Step 10: Execute the below command to build a container image.
docker build -t demo/webappcore:2.2.0
The above command will create a Docker image under demo path. With the image name called as webappcore and version 2.2.0.
Your output should look like below once it is successful:
PS C:\docker> docker build -t demo/webappcore:2.2.0 .
Sending build context to Docker daemon 9.853MB
Step 1/5 : FROM mcr.microsoft.com/dotnet/core/aspnet:2.2
---> 36e5a01ef28f
Step 2/5 : RUN mkdir C:\\app
---> Using cache
---> 8f88e30dcdd0
Step 3/5 : WORKDIR c:\\app
---> Using cache
---> 829e48e68bda
Step 4/5 : COPY WebAppCore2.2-master/Package/* c:/app/
---> Using cache
---> 6bfd9ae4b731
Step 5/5 : ENTRYPOINT ["dotnet", "WebAppCore2.2.dll"]
---> Running in 4b5488d5ea5f
Removing intermediate container 4b5488d5ea5f
---> 9729270fe1ac
Successfully built 9729270fe1ac
Successfully tagged demo/webappcore:2.2.0
Step 11: Once the image has been built, you are now ready to run the container. Execute the below command.
docker run --name webappcore --rm -it -p 8000:80 demo/webappcore:2.2.0
The above command will create a new container called webappcore with parameters.
--rmis used to automatically remove the container after it is shutdown.-itwill open a session into your container and output all the logs.-pis used for creating an external port and assigning it to the internal port of a container. Port 8000 is exposed to outside containers, and port 80 is used to access the app within the container.demo/webappcore:2.2.0is the path to the Docker image to run as a container.
Output of a running container
Step 12: Browsing your application from your local machine localhost:8000.
This is it! You ran your first Docker container in your local environment. Thank you for following the tutorial. Please comment below for any issue or feedback you would like to share.
Что такое Docker Desktop
Docker Desktop — это инструмент для работы с Docker-контейнерами на локальной машине. Он упрощает процесс разработки, тестирования и развертывания приложений, позволяя взаимодействовать с контейнерами как через консоль, так и через удобный интерфейс.
Ключевые особенности:
- понятный графический интерфейс,
- удобное управление образами и контейнерами,
- встроенные инструменты для мониторинга,
- возможность разработки и тестирования без привязки к серверу,
- поддержка работы с Docker Compose.
Если вы только начинаете изучение Docker и хотите разобраться в основах, рекомендуем ознакомиться с отдельным вводным обзором. В нем разобрали принципы работы Docker, его основные компоненты и решаемые задач. Из текста вы узнаете, как создать и запустить контейнер, а также какую роль играет Kubernetes в связке c Docker.
О системных требованиях
Перед установкой Docker Desktop важно выбрать подходящий бэкенд для работы с контейнерами: WSL 2 или Hyper-V. Оба имеют свои особенности, так что от выбора будут зависеть и системные требования. Далее в тексте разберемся, когда и какой бэкенд подойдет лучше.
Когда нужен WSL
WSL 2 (Windows Subsystem for Linux 2) — это усовершенствованная версия подсистемы Windows для Linux, которая использует виртуальную машину с реальным Linux-ядром. В отличие от первой версии, WSL 2 обеспечивает лучшую совместимость с Linux-инструментами, технологиями и приложениями, а также более высокую производительность.
Преимущества использования WSL 2 с Docker Desktop
Работа с Linux-контейнерами. Docker изначально разрабатывали для работы в Linux-среде, поэтому большинство контейнеров в Docker Hub — это образы, ориентированные на Linux. Использование WSL 2 предоставляет Docker Desktop полноценную Linux-среду на Windows.
Повышенная производительность. WSL 2 значительно ускоряет выполнение контейнеров, что особенно заметно в сравнении с WSL 1 или Hyper-V, о котором мы расскажем дальше. Это преимущество обеспечивает полноценное Linux-ядро, которое позволяет Docker работать гораздо быстрее и с меньшими накладными расходами.
Работа с файловой системой Linux. В WSL 2 можно монтировать файловую систему Linux, что позволяет работать с кодом и данными в нативной Linux-среде. Это особенно важно при разработке приложений, которые будут запускаться в Linux-контейнерах и требуют специфической настройки среды — например, прав доступа или структуры каталогов.
Когда нужен Hyper-V
Рассмотрим ключевые сценарии, в которых предпочтительнее использовать Hyper-V.
Если система не поддерживает WSL 2
Некоторые сборки системы не позволяют включать необходимые компонентов для работы WSL 2 В частности, это касается старых версий Windows, а также устройств, которые не поддерживают Windows 10 Pro или 11 Pro, — WSL 2 для них недоступна, так как требует включенной виртуализации на уровне системы. В таких случаях можно использовать Hyper-V для виртуализации контейнеров и запуска Docker Desktop.
Для работы с Windows-контейнерами
Docker Desktop поддерживает как Linux-, так и Windows-контейнеры. Однако последние требуют прямого взаимодействия с ядром Windows, а WSL 2 предоставляет только Linux-среду. Hyper-V позволяет запускать Windows-контейнеры благодаря виртуализации Windows-системы.
Для изоляции и обеспечения безопасности
Hyper-V создает полноценные виртуальные машины, обеспечивая строгую изоляцию контейнеров друг от друга и от хост-системы. Это может быть важно в корпоративной среде или при работе с чувствительными данными.
Разница между WSL 2 и Hyper-V
Если вам нужны Linux-контейнеры и высокая производительность — выбирайте WSL 2. Если же требуется строгая изоляция или работа с Windows-контейнерами, Hyper-V будет предпочтительнее. Подробнее о разнице по ключевым критериям — в таблице:
| Критерий | WSL 2 | Hyper-V |
| Производительность | Высокая (нативное Linux-ядро) | Низкая (работа через полноценную ВМ) |
| Изоляция | Относительно низкая | Высокая (контейнеры изолированы) |
| Типы контейнеров | Только Linux-контейнеры | Linux- и Windows-контейнеры |
Системные требования Docker Desktop
При использовании WSL 2 в качестве бэкенда
- WSL версии 1.1.3.0 или новее.
- Windows 11 64-bit Home / Pro / Enterprise / Education, версия 22H2 или новее.
- Windows 10 64-bit Home / Pro / Enterprise / Education, версия 22H2 (сборка 19045) или новее.
- Включенная функция WSL 2 в Windows. Подробная инструкция есть в документации Microsoft;
- 4 ГБ ОЗУ.
- Включенная аппаратная виртуализация в BIOS на вашей локальной машине.
При использовании Hyper-V в качестве бэкенда
- Windows 11 64-разрядная Enterprise / Pro / Education, версия 22H2 или новее.
- Windows 10 64-разрядная Enterprise / Pro / Education, версия 22H2 (сборка 19045) или новее.
- Включенная функция Hyper-V. Подробнее об установке — в документации Microsoft;
- 4 ГБ ОЗУ.
- Включенная аппаратная виртуализация в BIOS на вашей локальной машине.
Установка WSL 2
1. Откройте PowerShell от имени администратора и введите команду wsl —install. Она выполняет следующие действия:
- включает дополнительные компоненты WSL и платформы виртуальных машин;
- скачивает и устанавливает последнюю версию ядра Linux;
- задает WSL 2 в качестве среды по умолчанию;
- скачивает и устанавливает дистрибутив Ubuntu Linux.
2. После успешной установки всех компонентов перезапустите компьютер.
Первичная настройка
1. Откройте установленный дистрибутив с помощью меню Пуск — найдите установленный дистрибутив (Ubuntu).
2. При первом запуске системы нужно создать имя пользователя и пароль для дистрибутива Linux.
3. Первичная настройка завершена, можно приступать к использованию WSL 2.
Альтернативный вариант — запустить WSL через PowerShell. Для этого введите команду wsl и система предложит произвести первичную настройку.
Установка Hyper-V
Для установки компонентов Hyper-V откройте PowerShell от имени администратора и выполните команду:
Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Hyper-V -All
Она установит все компоненты для работы Hyper-V, после чего нужно будет перезапустить компьютер.
Проверить корректность установки Hyper-V можно с помощью команды:
Get-WindowsOptionalFeature -Online -FeatureName *hyper*|ft
Установка Docker с бэкендом WSL 2
- Скачайте дистрибутив Docker Desktop с официального сайта и запустите установщик. Галочки оставьте на всех пунктах.
- После установки перезайдите в учетную запись и откройте ярлык Docker Desktop.
- Если все прошло успешно, вы увидите интерфейс инструмента:
Установка Docker с бэкендом Hyper-V
1. Скачайте дистрибутив Docker Desktop с официального сайта и запустите установщик. В инсталляционном окне уберите галочку Use WSL 2 instead of Hyper-V.
2. После установки перезайдите в учетную запись и откройте ярлык Docker Desktop.
3. Если установка выполнена корректно, программа запустится без ошибок и вы увидите интерфейс:
Запуск контейнера
Рассмотрим запуск первого контейнера на примере самого популярного образа — hello-world.
Поиск и скачивание образа
Поскольку вы только установили Docker Desktop, в системе нет образов контейнеров, которые можно запустить. Исправим это.
- Перейдите в раздел Images и нажмите кнопку Search images to run.
- Введите hello-world. В текущем окне на выбор есть две кнопки: Pull и Run. Если планируете для начала просто скачать образ, то выбирайте Pull. Если скачать и сразу запустить — Run.
- Оставляем стандартные настройки для запуска.
Проверка работы контейнера
Чтобы посмотреть запущенные контейнеры, перейдите во вкладку Containers и выберите созданный на прошлом этапе. В нашем примере для него было автоматически сгенерировано имя determined_jennings. Открыв контейнер, вы увидите сообщение, если настройка установка прошла успешно.
Как настроить запуск Docker при старте Windows
Для автозапуска Docker Desktop при авторизации на компьютере достаточно поставить галочку в настройках: Settings → General → Start Docker Desktop when you sign in to your computer.
После этого Docker Desktop будет запускаться автоматически при включении устройства.
Запуск Docker в облаке
Docker Desktop — удобный инструмент для локальной работы, но в ряде случаев может потребоваться облачная инфраструктура:
- если мощности вашего ПК не хватает для работы с контейнерами;
- если нужна среда для тестирования без нагрузки на локальную машину;
- если вы работаете с ML/AI и нужны видеокарты для обучения моделей.
1. В панели управления в верхнем меню перейдем в раздел Продукты → Облачные серверы.
2. Нажмем кнопку Создать сервер.
3. Выберем имя, регион и сегмент пула. Важно учесть, что от сегмента зависят доступные конфигурации и стоимость. После создания сервера менять сегмент пула нельзя.
4. В качестве источника выберите готовый образ, приложение, свой образ, сетевой диск или снапшот. В нашем случае — приложение Containers Ready с настроенной Ubuntu 22.04. Оно содержит:
- Docker версии 27.0.3;
- плагины для запуска Docker Compose версии 2.11.1;
- Portainer версии 2.20.3 — графический интерфейс для мониторинга и управления Docker-контейнерами, образами и сетью Docker.
5. Конфигурацию для примера возьмем базовую — 2 vCPU и 2 ГБ RAM, а в поле Диски выберем SSD Быстрый на 20 ГБ. Важно: это минимальные требования. Рекомендуем выбирать параметры серверы, исходя из ваших задач.
Помимо прочего, на этапе создания сервера или позже вы можете добавить GPU. При этом объем ОЗУ, который выделяется серверу, может быть меньше указанного в конфигурации — ядро ОС резервирует ее часть. Выделенный объем на сервере можно посмотреть с помощью команды sudo dmesg | grep Memory.
6. Для работы Containers Ready сервер должен быть доступен из интернета. Для этого создадим приватную подсеть и подключим публичный IP-адрес. В поле Сеть выберем Приватная подсеть и добавим новый публичный адрес. Подробнее о настройке подсети можно узнать в документации.
6. Добавьте SSH-ключ в поле Доступ. Подробнее о его генерации можно узнать в отдельной инструкции.
7. Ознакомьтесь с ценой и нажмите кнопку Создать сервер.
Сервер готов к использованию! Подробности о создании сервера с Сontainers Ready вы можете найти в документации. Если вам нужно запускать контейнеры с ML-моделями на мощных видеокартах, развернуть облачные серверы с GPU можно за несколько минут. Они помогут ускорить обучение нейросетей без закупки дорогого оборудования.
