Как запустить docker контейнер на windows

Today, Microsoft announced the general availability of Windows Server 2016, and with it, Docker engine running containers natively on Windows. This blog post describes how to get setup to run Docker Windows Containers on Windows 10 or using a Windows Server 2016 VM. Check out the companion blog posts on the technical improvements that have made Docker containers on Windows possible and the post announcing the Docker Inc. and Microsoft partnership.

Before getting started, It’s important to understand that Windows Containers run Windows executables compiled for the Windows Server kernel and userland (either windowsservercore or nanoserver). To build and run Windows containers, a Windows system with container support is required.

Windows 10 with Anniversary Update

For developers, Windows 10 is a great place to run Docker Windows containers and containerization support was added to the the Windows 10 kernel with the Anniversary Update (note that container images can only be based on Windows Server Core and Nanoserver, not Windows 10). All that’s missing is the Windows-native Docker Engine and some image base layers.

The simplest way to get a Windows Docker Engine is by installing the Docker for Windows public beta (direct download link). Docker for Windows used to only setup a Linux-based Docker development environment (slightly confusing, we know), but the public beta version now sets up both Linux and Windows Docker development environments, and we’re working on improving Windows container support and Linux/Windows container interoperability.

With the public beta installed, the Docker for Windows tray icon has an option to switch between Linux and Windows container development. For details on this new feature, check out Stefan Scherers blog post.

Switch to Windows containers and skip the next section.

Switching to windows containers

Windows Server 2016

Windows Server 2016 is the where Docker Windows containers should be deployed for production. For developers planning to do lots of Docker Windows container development, it may also be worth setting up a Windows Server 2016 dev system (in a VM, for example), at least until Windows 10 and Docker for Windows support for Windows containers matures.

For Microsoft Ignite 2016 conference attendees, USB flash drives with Windows Server 2016 preloaded are available at the expo. Not at ignite? Download a free evaluation version and install it on bare metal or in a VM running on Hyper-V, VirtualBox or similar. Running a VM with Windows Server 2016 is also a great way to do Docker Windows container development on macOS and older Windows versions.

Once Windows Server 2016 is running, log in, run Windows Update to ensure you have all the latest updates and install the Windows-native Docker Engine directly (that is, not using “Docker for Windows”). Run the following in an Administrative PowerShell prompt:

Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force
Install-Module -Name DockerMsftProvider -Force
Install-Package -Name docker -ProviderName DockerMsftProvider -Force
Restart-Computer -Force

Docker Engine is now running as a Windows service, listening on the default Docker named pipe. For development VMs running (for example) in a Hyper-V VM on Windows 10, it might be advantageous to make the Docker Engine running in the Windows Server 2016 VM available to the Windows 10 host:

# Open firewall port 2375
netsh advfirewall firewall add rule name="docker engine" dir=in action=allow protocol=TCP localport=2375

# Configure Docker daemon to listen on both pipe and TCP (replaces docker --register-service invocation above)
Stop-Service docker
dockerd --unregister-service
dockerd -H npipe:// -H 0.0.0.0:2375 --register-service
Start-Service docker

The Windows Server 2016 Docker engine can now be used from the VM host by setting DOCKER_HOST:

$env:DOCKER_HOST = "<ip-address-of-vm>:2375"

See the Microsoft documentation for more comprehensive instructions.

Running Windows containers

First, make sure the Docker installation is working:

> docker version
Client:
Version:      1.12.1
API version:  1.24
Go version:   go1.6.3
Git commit:   23cf638
Built:        Thu Aug 18 17:32:24 2016
OS/Arch:      windows/amd64
Experimental: true

Server:
Version:      1.12.2-cs2-ws-beta
API version:  1.25
Go version:   go1.7.1
Git commit:   62d9ff9
Built:        Fri Sep 23 20:50:29 2016
OS/Arch:      windows/amd64

Next, pull a base image that’s compatible with the evaluation build, re-tag it and to a test-run:

docker pull microsoft/windowsservercore
docker run microsoft/windowsservercore hostname
69c7de26ea48

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 docker login 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.

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 microsoft/windowsservercore 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. localhost 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.

Summary

This post described how to get setup to build and run native Docker Windows containers on both Windows 10 and using the recently published Windows Server 2016 evaluation release. To see more example Windows Dockerfiles, check out the Golang, MongoDB and Python Docker Library images.
Please share any Windows Dockerfiles or Docker Compose examples your build with @docker on Twitter using the tag #windows. And don’t hesitate to reach on the Docker Forums if you have questions.

More Resources:

  • Sign up to be notified of GA and the Docker Datacenter for Windows Beta
  • Docker for Windows Server
  • Learn more about the Docker and Microsoft partnership

Эта статья даст вам полное представление о Docker Desktop для пользователей Windows и MAC. Мы изучим установку Docker Desktop на компьютерах с Windows и Mac. После установки мы также попытаемся выполнить некоторые операции Docker.

Docker Desktop — это собственное настольное приложение, разработанное Docker для пользователей Windows и MAC. Это самый простой способ запуска, сборки, отладки и тестирования приложений Dockerized.

Docker Desktop предлагает важные и наиболее полезные функции, такие как быстрые циклы редактирования, уведомления об изменениях файлов, встроенная поддержка корпоративной сети и гибкость для работы с собственным выбором прокси и VPN.

Docker Desktop состоит из инструментов для разработчика, приложения Docker, Kubernetes и синхронизации версий. Он позволяет вам создавать сертифицированные образы и шаблоны языков и инструментов.

Скорость, безопасность и выбор — все, что вам нужно для разработки и доставки контейнерных приложений, доступных на вашем рабочем столе, будет представлено вам.

Прежде чем перейти к процессу установки, давайте разберемся с его версиями.

Версии Docker

Docker в основном поставляется в двух версиях, в Community и ENterprise.

Community версия поставляется с бесплатным набором продуктов Docker. ENterprise корпоративная версия представляет собой сертифицированную контейнерную платформу, которая предоставляет коммерческим пользователям дополнительные функции, такие как безопасность образов, управление образами, оркестровка и управление средой выполнения контейнеров, но по разумной цене.

Мы начнем наше обучение с Community Edition. Контейнеры Docker, работающие в конкретной операционной системе, совместно используют ядро ​​ОС. Это означает, что мы не можем использовать ядро ​​Windows (хост) для запуска контейнеров Linux или наоборот. Чтобы проделать это, у нас есть Docker Desktop для Windows и MAC.

Выпуски Docker Desktop

Docker Desktop выпускается в двух вариантах.

  • Stable: как видно из названия, стабильный выпуск тщательно протестирован и может быть использован при разработке более надежных приложений. Его версии полностью синхронизированы с версиями Docker Engine.
  • Edge: эти версии состоят из всех новых и экспериментальных функций Docker Engine. Есть больше шансов ошибок, сбоев и проблем, которые могут возникнуть. Тем не менее, пользователи получат возможность ознакомиться с предстоящими функциями.

Docker на Windows

Есть два варианта Docker на Windows.

1. Использование Docker Toolbox

Docker Toolbox предоставляет набор легких инструментов.

  • Oracle virtual box
  • Docker Engine
  • Docker Machine
  • Docker compose
  • Kitematic GUI

Вышеуказанные инструменты устраняют необходимость развертывания отдельной виртуальной машины для запуска Docker. Просто установите исполняемый файл панели инструментов Docker непосредственно в Windows и начните разработку приложений. Требуется 64-битная ОС и Windows 7 или выше с включенным режимом виртуализации.

Но опять же, панель инструментов Docker — это оригинальная поддержка, предоставляемая в Windows для запуска Docker и его устаревшего решения для всех ОС Windows, которые не соответствуют требуемой конфигурации.

2. Использование Docker Desktop

Docker Desktop — это новейшая технология, используемая для Docker в Windows. Он заменяет виртуальную машину Oracle собственной технологией виртуализации, доступной в Windows, то есть Microsoft Hyper-V.

Он по-прежнему будет запускать Docker на Linux-машине, созданной под ним. Но на этот раз вместо виртуальной машины Oracle мы использовали нативный Microsoft Hyper-V.

Установка Docker на Windows

Вы можете скачать репозиторий Docker Desktop из Docker Hub.

Установка Docker на Windows

истемные требования:

  • Windows 10 или Windows Server 2016 Professional или Enterprise Edition
  • Поддержка Hyper-V.

Чтобы запустить Hyper-V, оборудование должно соответствовать следующим требованиям:

  • 64-битный процессор
  • > = 4 ГБ ОЗУ
  • Поддержка виртуализации оборудования на уровне BIOS

Следовательно, программная и аппаратная зависимость заключается в запуске Docker Desktop на Windows.

Установка Docker на macOS

Вы можете скачать репозиторий Docker Desktop из Docker Hub.  

Установка Docker на macOS

Системные требования:

  • MAC Hardware 2010 или новее с аппаратной поддержкой управления памятью и неограниченным режимом. Выполните команду kern.hv_support, чтобы проверить, поддерживает ли оборудование MAC инфраструктуру гипервизора.
  • MAC OS версии 10.13 или новее.
  • > = 4 ГБ ОЗУ
  • Virtual-Box до версии 4.3.30

Работа с образами

После установки проверьте версию установленного Docker Engine.

docker --version

Docker работает с доставкой и запуском контейнерных приложений. Вам либо нужно создать свое собственное контейнерное приложение, либо Docker поддерживает контейнерные образы в Docker Hub, и его можно легко загрузить с помощью простой команды docker run.

Здесь мы будем тянуть образ Redis.

docker pull redis

docker образ redis

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

Docker Container запускает образ Docker. Следующим шагом является запуск контейнера.

docker run -p 6379 Redis

docker запуск redis

Будет создан зашифрованный идентификатор контейнера. Вы можете быстро проверить состояние работающего экземпляра в Docker, нажав на Dashboard option.

Docker Desktop

Обязательно остановите контейнер, прежде чем удалять его из Docker Engine.

Docker Desktop

Возможности Docker Desktop

Существует множество преимуществ:

  • Поддерживает широкий спектр инструментов разработки.
  • Обеспечьте быстрый и оптимизированный способ создания и публикации контейнерного образа на любой облачной платформе.
  • Простота установки и настройки полной среды Docker
  • Повышение производительности благодаря встроенной виртуализации Hyper-V для Windows и HyperKit для MAC.
  • Возможность работать в Linux через WSL 2 на компьютерах с Windows.
  • Легкий доступ к работающим контейнерам в локальной сети.
  • Возможность поделиться любым приложением на облачной платформе, на разных языках и в разных средах.
  • Для обеспечения безопасности и актуальности выполняются автоматические обновления.
  • Включены последние версии Kubernetes.
  • Возможность переключения между Linux и Windows сервером на Windows.

Docker Desktop — это нативное приложение, разработанное на Windows и MAC OS для запуска, сборки и доставки контейнерных приложений или сервисов.

Однако

Docker Desktop предназначен не для производственной среды, а для рабочего стола и среды разработки.

Также рекомендуем прочитать:

  1. Docker для начинающих — технология контейнеров
  2. В чем разница между Docker и Kubernetes?
  3. Введение в Docker Hub и все, что вы должны знать о нем
  4. Как установить Docker на Ubuntu, Windows, Debian и CentOS?
  5. Kubernetes — Введение для начинающих
  6. Docker посмотреть запущенные контейнеры, запустить или остановить контейнеры

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 пользователь.

Docker containers become unavoidable for infrastructure development as it provides, Isolation, Simplicity, Rapid Continuous Deployment, and Faster Configuration with Security. Earlier, Docker has only used for Linux based applications as it is using the Linux kernel baseline for creating Containers. But Windows applications are widely used in Software development and Hence, windows developers need Docker Containers for Windows. In this article, we will discuss How to Create Docker Windows Containers from Docker Desktop.

Table of Contents

Docker Desktop Installation

Requirement

  • Minimum Windows 10 (Home and All other Editions)
  • Hyper-V (In-Built and can be Enabled)
  • Only 64bit Processor Architecture
  • Virtualization Enablement from Bios Level

Installation

  • Step-1: Download the “Docker Desktop for Windows” exe file from here (https://hub.docker.com/editions/community/docker-ce-desktop-windows/) and run it to install.
  • Step-2: Enable Docker Running Environment 1. For Windows Home – Enable Windows Subsystem for Linux (Instructions Here: https://docs.microsoft.com/en-us/windows/wsl/install-win10). 2. For Windows Other Editions – Enable Hyper-V (Instructions Here: https://docs.microsoft.com/en-us/virtualization/hyper-v-on-windows/quick-start/enable-hyper-v)
  • Step-3: Follow the instructions on the Installation process
  • Step-4: If you are the Only user with Admin access, you can proceed. Else add the current user into a docker-users group (Instructions Here: https://www.tenforums.com/tutorials/88049-add-remove-users-groups-windows-10-a.html)
NOTE:

Docker Desktop Installed in the Windows Machine can run Linux Based Docker Containers and Windows-based Docker Container. But You cannot run Windows Based Docker Containers on Docker Engine installed in Linux. Refer the below image.

Docker Host Table
Docker Host Table

About Docker on Windows Machine

As we all know, the Docker Engine will run as a daemon that uses the Linux specific kernel features. So, running the Docker Engine on Windows directly is not possible. Hence, we must create a Linux based environment in Windows to run docker. In order to enable Linux environment on the windows, we have two options,

  • Windows Subsystem for Linux (WSL) – is the compatibility layer to run Linux applications
  • Hyper-V – Microsoft solution for virtualization.
Docker on Windows Machine Architecture
Docker on Windows Machine Architecture

Both these features are available from Windows 10. Running docker on windows will be ultimately using the Linux environment. But it is using some of the Host’s features. So, Docker Engine will sit on top of the Linux Kernel created by the Hyper-V/WSL. On top of the Docker Engine, Docker Containers can be created. All this is managed by the Docker Desktop. So, Application Program which will be written by the developers will sit on top of the Containers.

Simple Windows Container with Example

Let’s learn how to create the Docker Windows container using Docker Desktop. For that, first, we are going to create Dockerfile which is the simple text file with the instructions of the application and configurations.

Creating Dockerfile

Let’s run a simple application which will return the “hello world” print output from the Windows Docker Container. For the same, create a file called “Dockerfile” and put the bellow content.

# Base Image
FROM microsoft/nanoserver

# Copy powershell init-script from the host machine (windows) to the docker container.
COPY init-setup.ps1 c:\\workspace\application\init-setup.ps1

# Run the Powershell script in the Docker Container
CMD ["powershell.exe", "c:\\workspace\application\init-setup.ps1"]
  • In this, Line number #2 is setting the container from the base image. Here it is “microsoft/nanoserver”.
  • Inline Number #5 is giving instructions to copy the init-script.ps1 from the host to the docker container.
  • Line Number #8 is to run the script in PowerShell executable.

And Create a script file called “init-setup.ps1” and put the below content inside the file

Building Docker Image

Once you have this file in your folder you can start building the Dockerfile as Docker image using the command.

$ docker build -t digitalvarys/print-hello-world .

where digitalvarys/print-hello-world is the tag name of the docker image.

Once the Docker image is been built, you can check the Image by passing the following commad

This will display the created image.

Running the Docker Container

Now, it is time to run the Docker image which we have created. Hence, run the following command

$ docker run digitalvarys/print-hello-world

This will print the string “hello world” as we provided.

If you run it with -it parameter, you can explore the Created Docker Container with Windows CMD.

ASP.net example of the Windows Docker Container.

The above sample application will tell you about the basic container feature. This one will tell you the real-time advantage of the Windows Docker Container.

Sample application  

For this tutorial, we are going to use, cloud foundry’s sample Dotnet core hello world application (https://github.com/cloudfoundry-samples/dotnet-core-hello-world). Just clone it and keep it in your working directory

Dockerfile creation.

Now, we are going to create Dockerfile to create the image of the above application.

# Base Image
FROM microsoft/dotnet:nanoserver-core

# Copy entire application code folder dotnet-application to the working directory in Container.
COPY c:\\workspace\dotnet-application .

# Relax the firewall rule to expose port 5000
EXPOSE 5000

# Run the dotnet application
CMD ["dotnet", "run", "--server.urls", "http://0.0.0.0:5000"]

Just like the PowerShell example, we are going to take the base image and copy the application from the host to the container. Then, we are going to expose the port 5000 to run the dotnet application in this port. Then, we are going to run the application using the dotnet executable.

Building the Docker Image.

Once the Dockerfile is ready, we have to build the Docker container.

$ docker build -t digitalvarys/simple-dotnet-application .

Here, I am giving the image name as “digitalvarys/simple-dotnet-application”.

Running the Docker Container

Now, we have to run the application in background (detached mode),

$ docker run -d -p 5000:5000 digitalvarys/simple-dotnet-application

This will run the container and expose the container port to the host port 5000.

Getting the IP address of the Created Docker Container.

Now, Just inspect the Docker container and see the assigned IP address of the running container,

$ docker inspect [container-id]

This will show you the JSON response. In that, check for “networks” -> “nat” -> “IPAddress”. This will be your container IP address.

Now, Just enter the URL in the browser as https://[container-ip-address]:5000, then you will see the Hello world message in the browser. This means your application is running in a container.

Conclusion

As we already discussed, Docker is unavoidable for the application development or at least in the process of application development. But the Containerization of the Windows application like dotnet application needs extra lookup. Hope this article covers enough concepts and procedures for the Windows Docker Containers running on windows application. In our upcoming article, we will discuss more running a cluster of Microsoft Windows-based applications in Docker Swarm and Kubernetes. Stay tuned and subscribe DigitalVarys for more articles and study materials on DevOps, Agile, DevSecOps and App Development.

Prabhu Vignesh Kumar

Experienced DevSecOps Practitioner, Tech Blogger, Expertise in Designing Solutions in Public and Private Cloud. Opensource Community Contributor.

When it comes to Docker containers, according to the usual thinking, that is Linux containers (LXC), not much to do with Windows, at best, is to run Docker containers in the Windows Linux virtual machine.

However, since Windows Server 2016, there are Windows-native Docker containers, which are no longer just for Linux, and Docker containers can now run Windows systems, with each Windows container sharing the host Windows kernel (–isolation= process,) or use a Windows kernel in a highly optimized virtual machine (–isolation=hyperv).

We say that since Windows Server 2016, including now Windows Server 2019, Windows Server 2022, and Windows 10 and 11 for desktop systems, with the help of Docker Desktop, you can also run Windows containers.

The original installation of Docker Desktop on Windows desktop can be used to run Linux containers, so it can be seen that on Windows desktop (e.g. Windows 7, 10, 11) two types of containers can be run

  • Linux containers: Each container runs a Linux instance, with resources isolated by the cgcroups namespace. By default, Docker Desktop’s LinuxEngine is used.
  • Windows containers: The containers run Windows instances in process isolation mode, where the containers share the host’s Windows kernel, and Hyper-V isolation mode, where the containers use the kernel of a highly optimized virtual machine. You need to enable the Hyper-V feature of Windows and switch Docker Desktop to use WindowsEngine.

By adding Windows containers to the traditional LXC concept, Docker’s architecture looks like this

Docker&rsquo;s architecture

Knowledge about Windows Docker containers can be found in Microsoft’s official documentation Containers on Windows Documentation.

The most basic images for Windows are the following four, listed in order of weight from heaviest to lightest.

  1. Windows: contains the full set of Windows APIs and system services (but not Server-related), such as Windows 10 image 20H2.
  2. Windows Server: Contains the full set of Windows APIs and system services, allowing the use of most service features, such as GPU acceleration if you need it.
  3. Windows Server Core: Includes only a subset of Windows Server APIs that are primarily used to support the .NET framework. Most services are also included (e.g. Fax service is not).
  4. Nano Server: The lightest Windows Server image, containing only some services that support the .NET Core API.

We can build our own image by choosing one of the above base images, or a quicker way is to choose an image where someone else has added the packages we need. For example, to run Python on Windows you can choose 3.10.2-windowsservercore-ltsc2022; https://mcr.microsoft.com/dotnet/framework/sdk:4.8 for .net sdk4.8.

For a rough comparison of the image file sizes (which vary greatly by version), here are the image sizes listed with docker images

  1. mcr.microsoft.com/windows:20H2 size 16.2G
  2. mcr.microsoft.com/windows/server:ltsc2022 size 11.4 G
  3. mcr.microsoft.com/windows/servercore:ltsc2022 size 4.96 G, mcr.microsoft.com/windows/servercore:ltsc2016 but 12 G
  4. mcr.microsoft.com/windows/nanoserver:ltsc2022 is 295 M in size, like an embedded system

It is only possible to pull/run/build Windows images on Windows platforms and requires that the current Windows platform be compatible with the image version, unlike Linux containers which do not have any requirements for the current platform. We will learn more about this later.

To install Docker on Windows Server (including the current Windows 2016, 2019, 2022), execute the following command in PowerShell.

1
Install-Module -Name DockerMsftProvider -Repository PSGallery -Force

If prompted to install NuGet, select Y. If the above command requires TLS, execute the following command first.

1
[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12;

Finally, install Docker.

1
Install-Package -Name docker -ProviderName DockerMsftProvider

To install Docker Desktop under Windows 10 or 11.

The next example is Windows 10 (also for Windows 11), to see the difference between the two container types (Linux/Windows), for which a clean system was installed, and the following is the hardware and software environment of the test machine.

  1. CPU: Intel i7-7700 @3.60GHz
  2. Memory: 48 GB
  3. Windows 10 Pro, 21H1, OS Version: 10.0.19043
  4. Docker Desktop 4.5.1 (74721), and its requirements for WSL 2
  5. Additional Windows features such as Containers, Hyper-V, Windows Hypervisor Platform are not yet enabled, but Virtual Machine Platform is found to be enabled by default

Linux containers on Windows

After just installing Windows 10 Pro + Docker Desktop, by default, LinuxEngine is used, so only Linux containers are supported, run docker version to see the server/client version.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
C:\Users\yanbin>docker version
Client:
 Cloud integration: v1.0.22
 Version:           20.10.12
 API version:       1.41
 Go version:        go1.16.12
 Git commit:        e91ed57
 Built:             Mon Dec 13 11:44:07 2021
 OS/Arch:           windows/amd64
 Context:           default
 Experimental:      true
 
Server: Docker Desktop 4.5.1 (74721)
 Engine:
  Version:          20.10.12
  API version:      1.41 (minimum version 1.12)
  Go version:       go1.16.12
  Git commit:       459d0df
  Built:            Mon Dec 13 11:43:56 2021
  OS/Arch:          linux/amd64
  Experimental:     false
 containerd:
  Version:          1.4.12
  GitCommit:        7b11cfaabd73bb80907dd23182b9347b4245eb5d
 runc:
  Version:          1.0.2
  GitCommit:        v1.0.2-0-g52b36a2
 docker-init:
  Version:          0.19.0
  GitCommit:        de40ad0

We see Server Engine OS/Arch: linux/amd64 above. The linux/amd64 of Server means that Docker can only run Linux containers.

At this point we can run the following command.

1
2
docker pull busybox
docker run busybox echo hello world!

It is also possible to build Linux images, such as Dockerfile content.

1
2
FROM ubuntu:20.04
CMD echo hello world!

Then execute the build and test.

1
2
docker build -t test .
docker run test

It is illegal to try to pull or run a Windows container at this point.

1
2
3
C:\Users\yanbin> docker pull mcr.microsoft.com/windows/nanoserver:20H2
20H2: Pulling from windows/nanoserver
no matching manifest for linux/amd64 in the manifest list entries

Of course, run/build Windows images don’t work either, because you have to pull the Windows image before run/build. The reason is that it doesn’t match the current linux/amd64.

Exploring Docker Desktop LinuxEngine for Windows

1
2
3
4
c:\Users\yabqi>docker context ls
NAME                TYPE                DESCRIPTION                               DOCKER ENDPOINT                             KUBERNETES ENDPOINT   ORCHESTRATOR
default *           moby                Current DOCKER_HOST based configuration   npipe:////./pipe/docker_engine                                    swarm
desktop-linux       moby                                                          npipe:////./pipe/dockerDesktopLinuxEngine

Go to the host of Docker.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
c:\Users\yanbin>docker run --net=host --ipc=host --uts=host --pid=host -it --security-opt=seccomp=unconfined --privileged --rm -v /:/host alpine chroot /host
root@docker-desktop:/# uname -a
Linux docker-desktop 5.10.16.3-microsoft-standard-WSL2 #1 SMP Fri Apr 2 22:23:49 UTC 2021 x86_64 GNU/Linux
root@docker-desktop:/# free
               total        used        free      shared  buff/cache   available
Mem:        39336428      586016    37845116      377180      905296    37951412
Swap:       10485760           0    10485760
root@docker-desktop:/# cat /proc/cpuinfo | grep processor
processor       : 0
processor       : 1
processor       : 2
processor       : 3
processor       : 4
processor       : 5
processor       : 6
processor       : 7

With 48G of physical memory, the Docker host can use up to 39G of memory and all 8 cores of the CPU. This is different from the default allocation of 2G RAM and half the total number of CPU cores in Docker Desktop under Mac OS X.

Note that Hyper-V is not enabled on Windows 10 so far, and the command to view the physical memory is 48G, the Docker host can use up to 39G of memory and all 8 cores of the CPU. This is different from the default allocation of 2G of memory and half the total number of CPU cores for Docker Desktop on Mac OS X.

Note that Hyper-V is not enabled on Windows 10 so far, check with the command.

1
2
3
4
5
6
7
8
9
PS C:\Windows\system32> Get-WindowsOptionalFeature -Online -FeatureName Microsoft-Hyper-V
 
 
FeatureName      : Microsoft-Hyper-V
DisplayName      : Hyper-V Platform
Description      : Provides the services that you can use to create and manage virtual machines and their resources.
RestartRequired  : Possible
State            : Disabled
CustomProperties :

Switching to use Windows containers

To use Windows containers in Windows 10, first switch to Windows containers for Docker Desktop by tapping Docker Desktop on the system bar and going to its context menu.

context menu

Or use the DockerCli command to switch

1
"c:\Program Files\Docker\Docker\DockerCli.exe" -SwitchWindowsEngine

If you want to switch back to LinuxEngine from WindowsEngine, the parameter is -SwitchLinuxEngine.

Or use the -SwitchDaemon parameter to switch back and forth between LinuxEngine and WindowsEngine.

1
c:\Program Files\Docker\Docker\DockerCli.exe" -SwitchDaemon

However, trying to switch to WindowsEngine, either through the UI or by command, now brings up an error container.

error

The reason for this is that Hyper-V is not turned on, which can be done in the Turn Windows features on or off interface.

Turn Windows features on or off interface

Or use the PowerShell command prompted earlier

1
Enable-WindowsOptionalFeature -Online -FeatureName $("Microsoft-Hyper-V", "Containers") -All

Windows will restart automatically after Hyper-V is turned on. After that, you can successfully switch Docker Desktop to Window containers mode by performing the previous step, and then check the docker version.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22

C:\Users\yanbin>docker version
Client:
 Cloud integration: v1.0.22
 Version:           20.10.12
 API version:       1.41
 Go version:        go1.16.12
 Git commit:        e91ed57
 Built:             Mon Dec 13 11:44:07 2021
 OS/Arch:           windows/amd64
 Context:           default
 Experimental:      true
 
Server: Docker Desktop 4.5.1 (74721)
 Engine:
  Version:          20.10.12
  API version:      1.41 (minimum version 1.24)
  Go version:       go1.16.12
  Git commit:       459d0df
  Built:            Mon Dec 13 11:42:13 2021
  OS/Arch:          windows/amd64
  Experimental:     false

The version information is displayed more simply, and we see that Server / OS/Arch has become windows/amd64.

If you try to run the Linux container at this point it won’t work either.

1
2
3
4
5
C:\Users\yanbin>docker run busybox
Unable to find image 'busybox:latest' locally
latest: Pulling from library/busybox
docker: no matching manifest for windows/amd64 10.0.19043 in the manifest list entries.
See 'docker run --help'.

Build and run Windows images/containers

1
2
C:\Users\yanbin>docker run mcr.microsoft.com/windows:20H2 cmd /c "echo hello world!"
hello world!

Build the Windows image with the following Dockerfile contents.

1
2
FROM mcr.microsoft.com/windows/servercore:ltsc2016
CMD echo hello world!
1
2
3
C:\Users\yanbin>docker build -t test .
C:\Users\yanbin>docker run test
hello world!

Docker Desktop under WindowsEngine

Switch to WindowsEngine and look at the docker context.

1
2
3
4
C:\Users\yanbin>docker context ls
NAME                TYPE                DESCRIPTION                               DOCKER ENDPOINT                               KUBERNETES ENDPOINT   ORCHESTRATOR
default *           moby                Current DOCKER_HOST based configuration   npipe:////./pipe/docker_engine                                      swarm
desktop-windows     moby                                                          npipe:////./pipe/dockerDesktopWindowsEngine

A desktop-windows appears instead of the previous desktop-linux.

As for the host of the Windows container, it is related to the isolation mode, there are two types, process isolation and Hyper-V isolation.

process isolation

It is similar to the cgroups naming isolation of Linux containers, all containers share the current system kernel, the container is actually a process under the current system. The current system is the host of the Windows container, which requires the running container to be of the same version as the current operating system, otherwise the kernel cannot be shared, and the following error will occur.

1
2
C:\Users\yanbin>docker run -it --isolation=process mcr.microsoft.com/windows/servercore:ltsc2016 ping localhost -t
docker: Error response from daemon: hcsshim::CreateComputeSystem 2cc0e4e8ce8c0f7e8c82bef76df4a9dbf0672d6ffe29776814891ce27c6bb3fe: The container operating system does not match the host operating system.

Similar to the Linux container, processes started with –isolation=process can be listed with the Get-Process command.

Hyper-V isolation

The default value of -isolation in the docker runtime is hyperv, where the container runs in a highly optimized virtual machine, and the container processes do not appear on the current system, but are wrapped in individual vmwp virtual machine processes. That is, that virtual machine is the host of the Windows container. But where can I see the supposedly highly optimized virtual machine? Not in Hyper-V Manager, not with the Get-VM command, too highly optimized.

Learned about the two isolation modes for Windows containers, which might explain why docker run -p 80:8080 ... The default hyperv isolation is 80 to the highly optimized virtual machine, not the current operating system, you should try with -isolation=process, just make sure the current system version and the container system version to be highly consistent. —– verified that even with –isolation=process -p 80:8080, the ports are still not mapped out.

And the speed of starting the container may be related to the choice of isolation mode, and then highly optimized virtual machine should also be slower than the process isolation way to start the container, because process isolation is essentially a local process. —– actual test seems to be not much different, anyway, are much slower than the Linux container, at least an order of magnitude difference.

On a particular Windows operating system, not all Windows images support process isolation, Hyper-V isolation is supported, refer to the Windows container version compatibility list Windows container version compatibility.

Windows system and container version compatibility

Knowing this can guide us in choosing what version of Windows to build images on and what version of Windows to run containers on. This is not a problem at all for Linux containers, because basically a Linux system that can run docker commands is free to build/run images of any Linux distribution. When you first encounter Windows containers, it is easy to get frustrated when you choose a Windows machine that can run docker commands as WindowsEngine, and you want to pull, run or build an image, but you still have the Linux container mindset in your head.

For example, pull the image of mcr.microsoft.com/windows/servercore:ltsc2022 on Windows 2016.

1
2
3
4
5
6
PS C:\docker> docker pull mcr.microsoft.com/windows/servercore:ltsc2022
ltsc2022: Pulling from windows/servercore
8f616e6e9eec: Extracting [==================================================>] 1.252 GB/1.252 GB
898469748ff6: Download complete
failed to register layer: re-exec error: exit status 1: output: ProcessUtilityVMImage C:\ProgramData\docker\windowsfilter\ce66a282a87a379aca443a594025eee342160907305a3f4323f2baaa38d89937\Util
ityVM: The system cannot find the path specified.

But pull mcr.microsoft.com/windows/servercore:ltsc2016 is fine. docker run/build based on incompatible image versions is also the same problem, because rub/build needs to be pulled first.

1
2
PS C:\> docker run mcr.microsoft.com/windows/servercore:ltsc2016 cmd /c "echo hello"
docker: Error response from daemon: hcsshim::CreateComputeSystem a9c5b39283e525ca8cbf688f95d7aaabfdd1eb7dd21914d9e587144a455125ca: The container operating system does not match the host operating system.

Therefore, a clear understanding of Windows system and container version compatibility is not likely to make us frustrated and even a bit frantic when we come into contact with Windows containers.

For Windows systems that correspond to Windows image versions, and whether Hyper-V or process isolation is supported, please refer to this list Windows container version compatibility. Basically, newer versions are compatible with older versions, e.g. Windows Server 2019 can run Windows Server 2019 and Windows Server 2016 under Windows Server 2019, and Windows Server 2022 can run all versions from Windows 2016 to Windows 2022. However, if process isolation is supported, the platform must be the same as the container version, e.g. Windows Server 2019 can only support Windows Server 2019 if the Windows container is run in process isolation.

Likewise, follow this compatibility table when pulling or building with docker. Build with a higher OS platform for broader compatibility, but use –isolation=process for the benefit of running containers with the exact same version.

This strict matching of Windows image versions to Windows hosts doesn’t defeat the purpose of running Linux containers, we can run other Linux containers in a Linux host without even caring what kernel version or distribution it is. It’s a bit like when Windows dabbled with Java and came up with Visual J++, which directly undermined Java’s claim to write once and run everywhere.

AWS support for Windows containers

I’ve been using Linux container services in ECS before, because I had to specify the image when defining the Task, and at that time I was not in the dark about Windows containers, so I always thought ECS didn’t support Windows containers at all. Only recently I noticed that AWS has provided a lot of optimized Windows Server ECS AMI to run docker Windows containers, for example.

1
2
3
4
5
6
7
8
Windows_Server-2016-English-Core-Containers-*
Windows_Server-2016-English-Full-ECS_Optimized-*
Windows_Server-2019-English-Core-Containers
Windows_Server-2019-English-Full-ECS_Optimized-*
Windows_Server-2022-English-Core-Containers-*
Windows_Server-2022-English-Full-ECS_Optimized-*
Windows_Server-20H2-English-Core-Containers
Windows_Server-20H2-Core-ECS_Optimized-*

etc.

The version of Windows can be obtained with the ver , systeminfo commands.

Attempting to use docker run --isolation=hyperv on the selected Windows_Server-2016-English-Core-Containers-2016 prompts that there is no hypervisor.

1
2
3
PS C:\docker> docker run --isolation=hyperv mcr.microsoft.com/windows/servercore:ltsc2016 cmd /c "echo hello"
C:\Program Files\Docker\docker.exe: Error response from daemon: container fba5ff713c0e9a4fc439747c6792251855c06dfcb1649c3e58d72280b9d62a23 encountered an error during CreateContainer: failure
in a Windows system call: No hypervisor is present on this system. (0xc0351000) extra info.......................

Although ECS supports Windows containers, Windows images are very large, starting at 10G, which is a beast compared to Linux images of about 100-200M, which can seriously affect the speed of building, pushing, and pulling images. And it’s also slower to start a Windows container after the image is downloaded. So for Windows applications you might want to run past the ECS and let the ELB connect directly to the EC2 Target Group.

Boot speed test

It is not yet possible to test the startup speed in different isolation modes for the same image, because the --isolation=hyperv isolation level cannot be used on Windows Server.

Windows containers in different isolation modes

Test the speed of booting Windows containers on Windows Server 2016 with process isolation and Hyper-V isolation respectively.

1
2
PS C:\docker> Measure-Command {docker run --isolation=process mcr.microsoft.com/windows/servercore:ltsc2016 cmd /c "echo hello" | Out-Host} | findStr TotalSeconds
TotalSeconds      : 6.1539651

The average time taken is 6.15 seconds.

This is not comparable to starting a Linux container under Linux.

1
2
3
4
5
$ time docker run ubuntu:20.04 echo hello
 
real    0m0.361s
user    0m0.019s
sys 0m0.005s

The time to boot a ubuntu:20.04 under Windows 10 is.

1
2
PS C:\Windows\system32> Measure-Command {docker run ubuntu:20.04 echo hello | Out-Host} | findStr TotalSeconds
TotalSeconds      : 1.7179686

Summary

The Windows container is not only big, but the Windows container is also slow to start.

here is still a problem with -p port mapping that does not start the corresponding port on the machine where the docker command is executed.

So we still support Linux where we can use it.

Port mapping problem (solved)

Running Windows Server Docker container

1
docker run --name aspnet_sample --rm -it -p 8080:80 mcr.microsoft.com/dotnet/framework/samples:aspnetapp

As usual with Linux containers, first use docker ps to verify that the port mapping is set (only Name and Ports are shown below)

1
2
PS C:\Windows\system32> docker ps --format "{{.Names}}: {{.Ports}}"
aspnet_sample: 0.0.0.0:8080->80/tcp

The port mapping is fine, from 8080 on the host to 80 on the container

First check if port 8080 is open on the host with a Linux-like netstat -na|grep 8080

1
2
PS C:\Windows\system32> netstat -na|findstr 8080
PS C:\Windows\system32>

Found nothing, then added telnet double authentication

1
2
PS C:\Windows\system32> telnet localhost 8080
Connecting To localhost...Could not open connection to the host, on port 8080: Connect failed

At this point, check the IP and port number of the container

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
PS C:\Windows\system32> docker exec aspnet_sample ipconfig
 
 
Ethernet adapter vEthernet (Container NIC 91439e0f):
 
    Connection-specific DNS Suffix  . : ec2.internal
    Link-local IPv6 Address . . . . . : fe80::e878:9772:931:e2cd%19
    IPv4 Address. . . . . . . . . . . : 172.25.8.94
    Subnet Mask . . . . . . . . . . . : 255.255.240.0
    Default Gateway . . . . . . . . . : 172.25.0.1
 
PS C:\Windows\system32> docker exec  aspnet_sample netstat -na|findstr 80
TCP 0.0.0.0:80 0.0.0.0:0 LISTENING
TCP [::]:80 [::]:0 LISTENING

The port 80 started in the container is fine, so accessing http://172.25.8.94:80 through the container IP is fine, but some places introduce access to http://172.25.8.94:8080 to access (this path does not work). And one reason is to use container IP in earlier versions, which earlier is not clear.

1
After the application starts, navigate to http://localhost:8080 in your web browser. You need to navigate to the application via IP address instead of localhost for earlier Windows versions

see https://hub.docker.com/_/microsoft-dotnet-framework-samples/?tab=description

The other day I’ve been troubled by this illusion, seeing port 8080 from netstat -na and telnet localhost 8080, and instinctively thinking that the Windows Server container port mapping is not working, and that further port mapping with it for ECS will not work. In fact, this is just a display bug, see Open issue: [Windows] Port binding is not visible with ’netstat’ but works correctly. #30300

In this case, the port mapping is actually successful, but you can’t access it with localhost:8080, use ipconfig to find the host IP, and then access the host IP:8080 is able to pass.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
PS C:\Windows\system32> ipconfig
 
........
 
Ethernet adapter Ethernet:
 
   Connection-specific DNS Suffix  . : ec2.internal
   Link-local IPv6 Address . . . . . : fe80::64ea:22d5:4620:79a8%4
   IPv4 Address. . . . . . . . . . . : 10.255.60.241
   Subnet Mask . . . . . . . . . . . : 255.255.255.0
   Default Gateway . . . . . . . . . : 10.255.60.1

Then

1
telnet 10.255.60.241 8080

There is no problem, that is, accessing http://10.255.60.241:8080 from the remote is possible, so naturally it is not a problem as a port mapping for ECS.

ECS

netstat -na is an illusion, localhost:8080 does not work either, nor does 127.0.0.1:8080, which means that docker -p 8080:80 when starting a Windows container only listens on port 8080 of the NIC, and is only visible to netstat -na, and even PowerShell command Get-NetTCPConnection are not visible. But one more -p 8080:80 will expose the problem.

1
2
PS C:\Windows\system32> docker run -p 8080:80 mcr.microsoft.com/dotnet/framework/samples:aspnetapp
C:\Program Files\Docker\docker.exe: Error response from daemon: failed to create endpoint dazzling_clarke on network nat: HNS failed with error : The object already exists.

Port 8080 is occupied, proving that 8080 is bound somewhere we can’t see.

Since then, using Windows containers in ECS is worth practicing further, and the following task is about how to control the size of the Windows Docker image and put it in the Docker Registry with a fast network.

  • Как запустить dmg файл на windows 10
  • Как запустить dirt 2 без windows live
  • Как запустить django на windows
  • Как запустить dism windows 10
  • Как запустить disciples 2 на windows 10