Docker: как развернуть фуллстек-приложение и не поседеть

ВведениеIntroduction

Windows Server 2016 — это первая версия ОС Windows со встроенной поддержкой технологии контейнеров.Windows Server 2016 is the first version of Windows to ship support for container technology built in to the OS. В Windows Server 2016 доступны два типа контейнеров: контейнеры Windows Server и контейнеры Hyper-V.In Server 2016, two types of containers are available: Windows Server Containers and Hyper-V Containers. Каждый тип поддерживает номера SKU Server Core и или Nano Server Windows Server 2016.Each container type supports either the Server Core or Nano Server SKU of Windows Server 2016.

Эти конфигурации по-разному влияют на производительность. Мы подробно рассмотрим их, чтобы вы могли выбрать подходящий вариант для своих сценариев.These configurations have different performance implications which we detail below to help you understand which is right for your scenarios. Кроме того, мы подробно опишем конфигурации, влияющие на производительность, и компромиссные решения с использованием каждого из этих вариантов.In addition, we detail performance impacting configurations, and describe the tradeoffs with each of those options.

Контейнер Windows Server и контейнеры Hyper-V предоставляют сходные возможности, предоставляющие сходные возможности переносимости и согласованности. Но они отличаются в контексте гарантий изоляции и показателей производительности.Windows Server Container and Hyper-V containers offer many of the same portability and consistency benefits but differ in terms of their isolation guarantees and performance characteristsics.

Контейнеры Windows Server обеспечивают изоляцию приложений используя соответствующую технологию в отношении процессов и пространств имен.Windows Server Containers provide application isolation through process and namespace isolation technology. Контейнер Windows Server использует ядро совместно с узлом контейнера и всеми остальными контейнерами на этом узле.A Windows Server container shares a kernel with the container host and all containers running on the host.

Контейнеры Hyper-V расширяют возможности изоляции, предоставляемые контейнерами Windows Server, ведь каждый контейнер запускается в высокооптимизированной виртуальной машине.Hyper-V Containers expand on the isolation provided by Windows Server Containers by running each container in a highly optimized virtual machine. В этой конфигурации ядро узла контейнера не используется совместно с контейнерами Hyper-V.In this configuration the kernel of the container host is not shared with the Hyper-V Containers.

Дополнительная изоляция, предоставляемая контейнерами Hyper-V, во многом достигается благодаря предоставляемому гипервизором уровню изоляции между контейнером и узлом контейнера.The additional isolation provided by Hyper-V containers is achieved in large part by a hypervisor layer of isolation between the container and the container host. Это влияет на плотность контейнеров (в отличие от контейнеров Windows Server системные и двоичные файлы используются совместно в меньшей степени), увеличивая общий объем хранилища и памяти.This affects container density as, unlike Windows Server Containers, less sharing of system files and binaries can occur, resulting in an overall larger storage and memory footprint. Кроме того, использование некоторых режимов использования сети, операций ввода-вывода для хранилища и ЦП может быть сопряжено с дополнительными издержками.In addition there is the expected additional overhead in some network, storage io, and CPU paths.

Server Core и Nano ServerNano Server and Server Core

Контейнеры Windows Server и контейнеры Hyper-V поддерживают Server Core, а для нового режима установки, доступного в Windows Server 2016, еще и Nano Server.Windows Server Containers and Hyper-V containers offer support for Server Core and for a new installation option available in Windows Server 2016 : Nano Server.

Nano Server: это удаленно управляемая серверная ОС, оптимизированная для частных облаков и центров обработки данных.Nano Server is a remotely administered server operating system optimized for private clouds and datacenters. Этот вариант аналогичен Windows Server в режиме основных серверных компонентов, однако значительно меньше по размеру, не имеет функций локального входа и поддерживает только 64-разрядные приложения, средства и агенты.It is similar to Windows Server in Server Core mode, but significantly smaller, has no local logon capability, and only supports 64-bit applications, tools, and agents. Он занимает гораздо меньше места на диске и запускается быстрее.It takes up far less disk space and starts faster.

Building and pushing Windows container images

Pushing images to Docker Cloud requires a free Docker ID. Storing images on Docker Cloud is a great way to save build artifacts for later user, to share base images with co-workers or to create build-pipelines that move apps from development to production with Docker.

Docker images are typically built with docker build from a Dockerfile recipe, but for this example, we’re going to just create an image on the fly in PowerShell.

"FROM microsoft/windowsservercore `n CMD echo Hello World!" | docker build -t <docker-id>/windows-test-image -

Test the image:

docker run <docker-id>/windows-test-image
Hello World!

Login with and then push the image:

docker push <docker-id>/windows-test-image

Images stored on Docker Cloud available in the web interface and public images can be pulled by other Docker users.

Предварительные требованияPrerequisites

  • Docker DesktopDocker Desktop
  • Visual Studio 2019 с рабочей нагрузкой Веб-разработка, Средства Azure и (или) Кроссплатформенная разработка .NET Core.Visual Studio 2019 with the Web Development, Azure Tools workload, and/or .NET Core cross-platform development workload installed
  • Средства разработки .NET Core для разработки с использованием .NET Core..NET Core Development Tools for development with .NET Core.
  • Для публикации в Реестр контейнеров Azure требуется подписка Azure.To publish to Azure Container Registry, an Azure subscription. Зарегистрируйтесь для получения бесплатной пробной версии.Sign up for a free trial.

Automated pipeline to build the test machines

The Azure VM images we use to spin up WSL 2 test machines are created with a separate CI pipeline. We use Packer to create the VM image from an ISO file and run provision scripts to prepare everything we need to run it as a CI runner. The pipeline of how we build and upload the VM image also contains more than just the build step. We first check the source code of the Packer template and the PowerShell and Unix shell scripts to fail fast if a code change broke something. The Packer build itself takes the longest time, it also runs a Windows Update in the VM to get the latest OS version. After the build we added a verification step using InSpec to check if the software we need is installed correctly.

The output of this Packer pipeline is an Azure VM image that can be used to spin up new on-demand runners in other CI pipelines. We normally run some tests in a canary environment to see if the VM image really boots up and attaches to our CI infrastructure. If everything is fine we update the configuration for the Docker Desktop CI for our end-to-end tests.

Журналы контейнеров DOCKERDocker Container Logs

Команда извлекает журналы контейнера из stdout/stderr, стандартные расположения депозита журнала приложений для приложений Linux.The command fetches a container’s logs from STDOUT/STDERR, the standard application log deposit locations for Linux applications. Приложения Windows обычно не выполняют вход в STDOUT/STDERR; Вместо этого они регистрируются в ETW, журналах событий или файлах журналов.Windows applications typically do not log to STDOUT/STDERR; instead, they log to ETW, Event Logs, or log files, among others.

Монитор журнала, поддерживаемый корпорацией Майкрософт инструмент конвертер, теперь доступен на сайте GitHub.Log Monitor, a Microsoft-supported opensource tool, is now available on github. Монитор журнала связывает журналы приложений Windows с STDOUT/STDERR.Log Monitor bridges Windows application logs to STDOUT/STDERR. Монитор журнала настраивается с помощью файла конфигурации.Log Monitor is configured via a config file.

Журнал использования монитораLog Monitor Usage

LogMonitor.exe и LogMonitorConfig.jsдолжны быть включены в один и тот же каталог Логмонитор.LogMonitor.exe and LogMonitorConfig.json should both be included in the same LogMonitor directory.

Монитор журнала может использоваться в шаблоне использования оболочки:Log Monitor can either be used in a SHELL usage pattern:

Или шаблон использования ENTRYPOINT:Or an ENTRYPOINT usage pattern:

Оба примера использования заключают приложение ping.exe.Both example usages wrap the ping.exe application. Другие приложения (например, IIS). Сервицемонитор) может быть вложен с монитором журнала подобным образом:Other applications (such as IIS.ServiceMonitor) can be nested with Log Monitor in a similar fashion:

Монитор журнала запускает приложение с оболочкой как дочерний процесс и отслеживает выходные данные STDOUT приложения.Log Monitor starts the wrapped application as a child process and monitors the STDOUT output of the application.

Обратите внимание, что в шаблоне использования оболочки инструкция CMD/ENTRYPOINT должна быть указана в форме оболочки и не Exec.Note that in the SHELL usage pattern the CMD/ENTRYPOINT instruction should be specified in the SHELL form and not exec form. Если используется Exec-форма инструкции CMD/ENTRYPOINT, ОБОЛОЧКа не запускается, а средство «монитор журналов» не запускается в контейнере.When exec form of the CMD/ENTRYPOINT instruction is used, SHELL is not launched, and the Log Monitor tool will not be launched inside the container

Дополнительные сведения об использовании можно найти на вики-сайте монитора журнала.More usage information can be found on the Log Monitor wiki. Примеры файлов конфигурации для ключевых сценариев контейнеров Windows (IIS и т. д.) можно найти в репозитории GitHub.Example config files for key Windows container scenarios (IIS, etc.) can be found within the github repo. Дополнительный контекст можно найти в этой записи блога.Additional context can be found in this blog post.

Using docker-compose on Windows

Docker Compose is a great way develop complex multi-container consisting of databases, queues and web frontends. Compose support for Windows is still a little patchy and only works on Windows Server 2016 at the time of writing (i.e. not on Windows 10).

To develop with Docker Compose on a Windows Server 2016 system, install compose too (this is not required on Windows 10 with Docker for Windows installed):

Invoke-WebRequest https://dl.bintray.com/docker-compose/master/docker-compose-Windows-x86_64.exe -UseBasicParsing -OutFile $env:ProgramFiles\docker\docker-compose.exe

To try out Compose on Windows, clone a variant of the ASP.NET Core MVC MusicStore app, backed by a SQL Server Express 2016 database. A correctly tagged image is required before starting.

git clone https://github.com/friism/Musicstore
...
cd Musicstore
docker-compose -f .\docker-compose.windows.yml build
...
docker-compose -f .\docker-compose.windows.yml up
...

To access the running app from the host running the containers (for example when running on Windows 10 or if opening browser on Windows Server 2016 system running Docker engine) use the container IP and port 5000. will not work:

docker inspect -f "{{ .NetworkSettings.Networks.nat.IPAddress }}" musicstore_web_1
172.21.124.54

If using Windows Server 2016 and accessing from outside the VM or host, simply use the VM or host IP and port 5000.

My Docker installation on a Linux VM

Update package utility:

sudo apt-get update

Install packages:

sudo apt-get install apt-transport-https ca-certificates curl software-properties-common

Do the GPG key thing:

curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -

Check the key. Below is for what I installed. Visit the page for the latest instructions.

sudo apt-key fingerprint 0EBFCD88

Download the repository; (below is when using Ubuntu base version of Linux Mint 19 Tara):

sudo add-apt-repository “deb  https://download.docker.com/linux/ubuntu bionic stable”

Update:

sudo apt-get update

Install the latest Docker CE:

sudo apt-get install docker-ce

Verify Docker CE:

sudo docker run hello-world

If it works, you will get some text that tells your installation is working.

Docker Tools Setup

For this section, you’ll need to install the following tools using PowerShell in admin mode. These tools are packaged inside the Docker for Windows installer. Since the installer refuses to run on Windows 10 Home, we’ll install these programs individually using Chocolatey:

Once the installation process is complete, you can switch back to Git Bash terminal. You can continue using PowerShell, but I prefer Linux syntax to execute commands. Let’s execute the following commands to ensure Docker is running:

If all the above commands run successfully, it means you’ve successfully installed Docker. If you want to try out a more ambitious example, I have a small Node.js application that that I’ve configured to run on Docker containers. First, you’ll need to install GNU Make using PowerShell with Admin privileges:

Next, execute the following commands. Running this Node.js example will ensure you have no problem with exposed ports and mounting volumes on the Windows filesystem. First, navigate to a folder that that you’ve already mounted in VirtualBox settings. Next, execute the following commands:

When you hit the last command, you should expect a similar output:

Getting the above output means that volume mounting occurred successfully. Open to confirm that the website can be accessed. This will confirm that you have properly configured the ports. You can edit the source code, for example change the title in . As soon as you save the file, the browser page should refresh automatically. This means hot module reloading works from a Docker container.

I would like to bring your attention to the file in use. For hot module reloading to work from a Docker Container in Windows requires the following:

  1. When using parcel, specify HMR port in your start script:

    parcel src/index.html –hmr-port 1235

  2. In the VM’s Port Forwarding rules, make sure these ports are exposed to the host system:

    • 1234
    • 1235
  3. doesn’t work on filesystems, so file changes can’t be detected. The workaround is to set polling for via environment variables in . Here’s the full file so that you can see how it’s set:

Now that we have a fully working implementation of Docker on Windows 10 home, let’s set it up on WSL2 for those who are interested.

Initial Setup

You may or may not have the following applications installed on your system. I’ll assume you don’t. If you do, make sure to upgrade to the latest versions. I’m also assuming you’re running the latest stable version of Windows. At the time of writing, I’m using Windows 10 Home version 1903. Let’s start installing the following:

  1. Install Git Bash for Windows. This will be our primary terminal for running Docker commands.

  2. Install Chocolatey, a package manager for Windows. It will make the work of installing the rest of the programs easier.

  3. Install VirtualBox and its extension. Alternatively, If you have finished installing Chocolatey, you can simply execute this command inside an elevated PowerShell terminal:

  4. If you’d like to try running Docker inside the WSL2 environment, you’ll need to set up WSL2 first. You can follow this tutorial for step-by-step instructions.

Поддержка Docker ComposeDocker Compose support

Если требуется создать многоконтейнерное решение с помощью Docker Compose, добавьте в проекты поддержку оркестрации контейнеров.When you want to compose a multi-container solution using Docker Compose, add container orchestration support to your projects. Это позволит выполнять и отлаживать группу контейнеров (всего решения или группы проектов) одновременно, если они определяются в одном файле docker-compose.yml.This lets you run and debug a group of containers (a whole solution or group of projects) at the same time if they’re defined in the same docker-compose.yml file.

Чтобы добавить поддержку оркестрации контейнеров с помощью Docker Compose, щелкните правой кнопкой мыши узел решения или проекта в обозревателе решений и выберите Добавить > Поддержка оркестратора контейнеров.To add container orchestration support using Docker Compose, right-click on the solution or project node in Solution Explorer, and choose Add > Container Orchestration Support. Затем выберите Docker Compose для управления контейнерами.Then choose Docker Compose to manage the containers.

После добавления поддержки оркестрации контейнеров в проект в него добавится файл Dockerfile (если его не было прежде), а в само решение — папка docker-compose, как показано на следующем снимке экрана обозревателя решений:After you add container orchestration support to your project, you see a Dockerfile added to the project (if there wasn’t one there already) and a docker-compose folder added to the solution in Solution Explorer, as shown here:

Если файл docker-compose.yml уже существует, Visual Studio просто добавит в него необходимые строки кода конфигурации.If docker-compose.yml already exists, Visual Studio just adds the required lines of configuration code to it.

Повторите этот процесс с другими проектами, которыми нужно управлять с помощью Docker Compose.Repeat the process with the other projects that you want to control using Docker Compose.

Initial limitations

We are still working on polishing the Linux Workspace experience. Initially, you will have to deal with those following limitations:

  1. You can only mounts files backed by your distro VHD (that means you can’t bind mounts things within /tmp, /mnt, /var/run, /proc, /sys etc.). For most people, this should not be a problem, but mounting things like /var/run/docker.sock in a container won’t work initially. We are working with Microsoft on solving this issue, a future Windows Update will bring full bind mount support.
  2. We don’t provide client binaries yet. You need to install the docker cli and plugins using apt, yum or any other package manager on your distro. We will automate this in a later update.

Установка Docker в RPM-дистрибутивах Linux

На самом деле, процесс установки Docker довольно простой и понятный. Сейчас мы рассмотрим установку Docker в RPM-дистрибутивах (англ. «Red Hat Package Manager») операционной системы Linux. К данным дистрибутивам относятся следующие:

   Fedora

   CentOS

   Red Hat Enterprise Linux

В моём случае, это Fedora 31.

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

Далее добавляем стабильный репозиторий Docker:

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

Если команда запросит подтверждение GPG-ключа (англ. «GNU Privacy Guard»), то проверьте, совпадает ли фингерпринт со значением . Если совпадает, то подтверждайте.

Fedora 31 может возвратить вам исключение , поэтому для решения данной проблемы вы должны включить обратную совместимость для следующей командой:

Дальше вам нужно запустить daemon-сервис:

Чтобы проверить, что процесс установки прошёл успешно, вы можете запустить следующую команду:

Последним шагом является добавление пользователя в группу Docker, чтобы запускать команды Docker без прав суперпользователя:

Поздравляю, вы успешно установили Docker в RPM-дистрибутиве Linux!

Final Thoughts

I’ve switched to Windows and WSL 2 development for the past two months and I can’t describe how happy I am with my development workflow. Using Docker Desktop for WSL 2 for the past couple of days seems really promising, and most of the current issues of using Docker in WSL 2 seem to be resolved. I can’t wait for what comes next!

The only thing currently missing in my opinion is integration with VS Code   Remote Containers (instead of Remote WSL which was used for this blogpost) would allow you to run all your tooling within your Docker container.

Until VS Code Remote Containers support is ready, you can run to install the application dependencies on WSL 2, allowing VS Code to provide auto-complete and use all the nice tools included to help in development.

Setup your virtual machine

The example below is from my installation. Please use your specific details where necessary.

  1. Click on the Oracle VM Virtual Box icon
  2. Click New and step through the dialog boxes,
  3. Enter a Name “Linux Mint 19”, SelectType: Linux, SelectVersion: Ubuntu (see example)
  4. Memory Size: 4096,
  5. Hard Drive: Choose Create a virtual hard disk now,
  6. Hard Disk file type: VDI,
  7. Storage on physical hard disk: Dynamically allocated,
  8. File location and size: 20.00GB,
  9. Once the virtual machine is setup click Start on the Virtual Box menu (see example),
  10. Choose the Linux file (.iso) on your local machine when Virtual Box asks for it,
  11. Install your Linux distribution (distro) on your guest machine.

I used Linux Mint for my distro. If you happen to see a distorted/pixelated screen try these remedies.

Why did we do that?

When we released the tech preview, what we wanted was to put in the hands of real users, something that represents the vision we have about the future of Linux container development on Windows. We worked very quickly, aside from our main Docker Desktop project to build something we could experiment with, and collected a lot of user feedback (thank you Windows Insiders by the way, this helped a lot!).

We also challenged the tech preview architecture in term of long term concerns such as maintenance costs, problems diagnostics, stability, update handling, code sharing with other backends etc.

We then went back to the whiteboard, designed a few potential alternative architectures, and found that with minimal effort, we would be able to run our LinuxKit VM, with very small modifications, in a container within WSL 2. This approach makes it really easy to implement the same exact mechanisms as we have today for things like problems diagnostics, handling updates, ensuring version pack support, and feature parity with our other backends.

We went to a prototyping phase that proved successful and went on to integrate it directly in our Docker Desktop codebase.

Создание приложений для контейнера машинного обучения WindowsBuild Apps the for Windows ML container

Примеры для контейнера машинного обучения WindowsSamples for Windows ML container

Чтобы приступить к работе, убедитесь, что Visual Studio 2019 настроена и настраивается в соответствии с приведенными выше инструкциями.To get started, make sure your Visual Studio 2019 is set up and configured according to the above instructions. Затем попробуйте выполнить следующие примеры:Then, try the following samples:

  • Кустомвисион.CustomVision. В этом примере используется модель, обученная Пользовательская служба визуального распознавания Azure.This sample uses the model trained by Azure Custom Vision Service. Обученная модель экспортируется как файл ONNX и входит в состав примера приложения, выполняемого внутри контейнера.The trained model is exported as an ONNX file, and included as part of the sample app that runs inside the container.
  • Скуизенетобжектдетектион.SqueezeNetObjectDetection. Это приложение (только для# cpp и c) использует модель Скуизенет для обнаружения основного объекта в изображении.This app (cpp and c# only) uses the SqueezeNet model to detect the predominant object in an image.

Контейнер Windows ML поддерживает только подмножество API Windows из-за небольшого размера.Windows ML container only supports a subset of Windows APIs due to its small size. При создании проекта Visual Studio можно указать эту меньшую поверхность API, чтобы обнаружить неподдерживаемые API до выполнения.When you create a Visual Studio project, you can specify this smaller API surface, to detect unsupported APIs before runtime.

Чтобы использовать неавтономный контракт API WinRT:To use the Headless WinRT API contract:

  1. В Visual Studio 2019 создайте новый проект консольного приложения C# (.NET Core) .In Visual Studio 2019, create a new C# Console App (.NET Core) project.

  1. Выберите инструменты-> NuGet — консоль диспетчера пакетов >Select Tools->Nuget->Package Manager Console

  2. В консоли диспетчера пакетов выполните:In the Package Manager Console, run:

Создание проекта Visual Studio 2019 C++ с нуляCreate a Visual Studio 2019 C++ project from scratch

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Adblock
detector