Containers windows 10 что это

Содержание:


  • 1.

    Предыстория


  • 2.

    Windows контейнер


  • 3.

    В мире контейнеров Windows


  • 4.

    Связь с Docker


  • 5.

    Мир Windows

Начиная с Windows Server 2016 в операционной системе от Microsoft включена нативная поддержка контейнеров. Это не Linux контейнеры, это контейнеры, которые работают на Windows, и запускают Windows внутри себя.

Данный факт является результатом присоединения Microsoft к Open Container Initiative (OCI). Контейнеры в Windows позволяют запускать приложения, которые изолированы от остальной части системы в переносимых контейнерах. Эти контейнеры включают в себя все, чтобы ваше приложение было полностью функциональным. Так же как это произошло с Linux, Microsoft надеется, что контейнеры изменят характер поставки программного обеспечения для пользователей и в Windows.

Предыстория

Контейнеры являлись основой вычислений в Linux в течение целого ряда лет. Google, например, уже очень давно использует решения, основанные на контейнерах по всей своей империи, чтобы предоставлять распределенные приложения не только своим сотрудникам, но и своим пользователям по всему миру.

Тем не менее, Google не был долгое время одинок в своем увлечении контейнерными вычислениями. В какой-то момент из ниоткуда появился Docker, который в отличии от Google стандартизировал процессы доставки контейнеров, а также управления ими. Более того, Docker развивался сообществом энтузиастов в мире открытого исходного кода, что сделало его простым и очень популярным решением. С развитием проекта Docker буквально у каждого желающего появилась возможность получить скорость, гибкость и простоту управления программным обеспечением и инфраструктурой, которую предоставляют контейнеры.

Docker революция стала настолько значительной, что даже Microsoft присоединился к этой инициативе в первую очередь за счет поддержки Docker и Linux в Azure, а теперь и за счет интеграции этой технологии в Windows Server 2016. Самое интересное это то, что контейнеры Windows Server не основаны на Linux, это нечто совершенно новое. Windows контейнеры — это контейнеры, которые работают в Windows и запускают Windows внутри себя.

Причем Microsoft настолько серьезно стала относится к контейнерам, что сейчас активно участвует в Open Container Initiative (OCI), пытаясь перетягивать одеяло на себя так, как будто бы она сама придумала эту технологию.

Windows контейнер

Контейнер в Windows имеет много общего с его аналогом в Linux. Оба обеспечивают изолированную среду для запуска приложений. И там и там контейнеры используют передовые технологии изоляции для обеспечения портативной, но одновременно ограниченной среды, которая включает в себя практически все, чтобы приложение могло быть полностью функциональным.

Контейнер очень похож на виртуальную машину (ВМ) и часто рассматривается как отдельный тип виртуализации, но это два совершенно разные понятия. Да, каждый работает под управлением операционной системы (ОС), предоставляет внутри себя локальную файловую систему и может быть доступен по сети так же как физический компьютер. Тем не менее, при использовании ВМ вы имеете дело с полной и независимой ОС вместе с виртуальными драйверами устройств, управлением памятью и другими компонентами, которые добавляют к накладные расходы.

Контейнер переиспользует большее количество общих ресурсов хост-системы нежели виртуальная машина, а значит, он более легкий, быстрее разворачивается и проще масштабируется между различными датацентрами. Таким образом, контейнер может предложить более эффективный механизм для инкапсулирования приложения, обеспечивая ему при этом необходимые интерфейсы хост-системы — все из этого приводит к более эффективному использованию ресурсов и улучшению переносимости приложений.

Microsoft планирует предложить два типа контейнеров в Windows Server 2016: контейнер Windows Server и Hyper-V контейнер. Оба типа функционируют одинаковым образом, и могут быть созданы и управляются одинаково. Там, где они различаются — это в уровне изоляции, который каждый из них обеспечивает.

Контейнер Windows Server разделяет ядро с ОС работает на хост-машине, что означает, что все контейнеры, работающие на этой машине, разделяют одно и то же ядро. В то же время, каждый контейнер поддерживает свой собственный вид на операционную систему, реестр, файловую систему, IP-адреса и другие компоненты, сочетая это с изоляцией, предоставляемой каждому контейнеру при помощи процессов, пространства имен и технологий управления ресурсами.

Контейнер Windows Server хорошо подходит для ситуаций, в которых и основная ОС, и приложения в контейнерах лежат в пределах той же зоны доверия, например для приложений, которые охватывают несколько контейнеров или образуют общую службу. Тем не менее, контейнеры Windows Server обсуждаются в связи с их зависимостью от процесса обновления ОС хост-системы, который может осложнить обслуживание и препятствовать процессам. Например, патч примененный к хосту может сломать приложение, работающее в контейнере. Что еще более важно, в таких ситуациях, как многопользовательские среды, модель разделяемого ядра может раскрыть систему для уязвимостей приложений и кросс-контейнерных атак.

docker-windows.png

Hyper-V контейнер решает эти проблемы, предоставляя виртуальную машину, в которой нужно запустить контейнер Windows. При таком подходе контейнер больше не разделяет ядро хост-машины и не имеет зависимости от патчей ОС этой машины. Конечно, такой подход означает некоторую потерю скорости и эффективности упаковки, которые вы получаете с обычным контейнером в Windows Server, но взамен вы получаете более изолированную и безопасную среду.

Вне зависимости от типа контейнера, который вы используете, теперь у вас есть возможность использовать контейнеры с такими технологиями Windows как .NET или PowerShell, что не было возможно раньше. Контейнер для Windows предоставляет все необходимое для обеспечения работы приложения на любом компьютере под управлением Windows Server 2016, давая вам тот уровень переносимости, который был не доступен на протяжении большей части истории Windows. Вы можете создавать свои контейнеры локально, делать их доступными процессов для тестирования и контроля качества, а затем отправить их в команде, занимающейся продуктивом, без необходимости беспокоиться о сложных установках и конфигурациях на каждом шаге этого пути.

В мире контейнеров Windows

Ряд компонентов принимают участие в процессе создании и запуска контейнеров, начиная с хоста, на котором они должны работать. Хост может быть как физическим компьютером, так и ВМ с Windows 2016 Server. Единственное, что важно, чтобы была включена функция контейнеризации для Windows.

Вы можете разместить контейнеры на любой версии Windows: Server Full UI или же Core, которая устанавливается по умолчанию. Microsoft также представляет Nano издание для Windows Server 2016 — минимальную версию ОС, которая не включает в себя локальный графический пользовательский интерфейс или консоль.

Microsoft также добавила вложенную виртуализацию для Windows Server 2016, так что вы можете запустить Hyper-V контейнеры, если хостом является ВМ. Если вы планируете запускать такой тип контейнера, необходимо включить функцию Hyper-V на хост-ОС. Microsoft также добавляет поддержку контейнера для Windows 10, хотя только для Hyper-V контейнеров.

Как и с контейнерами Docker, вы разворачиваете контейнеры для Windows из образов. Каждый образ начинается с образа ОС контейнера — базового образа, включающего в себя операционную систему, которая будет работать внутри контейнера. В настоящее время Microsoft предоставляет два базовых образа: образ Server Core и образ Nano Server. Вы должны загрузить хотя бы один из этих образов ОС от Microsoft, прежде чем сможете развернуть контейнер.

Microsoft строго определяет, какие образы вы можете использовать с каким типом контейнера на основании хост-ОС, как описано в следующей таблице.

Хост-ОС

Контейнер Windows Server

Контейнер Hyper-V

Windows Server Full UI

Образ Server Core

Образ Nano Server

Windows Server Core

Образ Server Core

Образ Nano Server

Windows Server Nano

Образ Nano Server

Образ Nano Server

Windows 10

N/A

Образ Nano Server

Как вы можете видеть, Hyper-V контейнеры в настоящее время поддерживают только образ Nano сервера, но ваш выбор контейнеров Windows Server зависит от того, с какой версией Windows Server вы работаете.

Для этого типа контейнера, образ ОС должен также соответствовать хост-системы в отношении сборки и уровня обновления. Несоответствие может привести к непредсказуемому поведению как для контейнера, так и хоста. Это означает, что вы должны обновить образ базового контейнера ОС при обновлении ОС хоста. Это также означает, что вы не будете иметь возможность запускать Linux контейнер на Windows машине, или наоборот, и это также верно для Hyper-V контейнеров.

Образы обеспечивают высокую степень гибкости, когда речь идет о развертывании контейнеров. Вы можете создавать образы на основе существующего образа и обновлять новые образы так часто, как это необходимо. После этого вы можете развернуть один или несколько контейнеров из этого образа.

Например, предположим, что вы создаете образ, основанный на Server Core. В новый образ, вы устанавливаете приложение, которое в настоящее время находится в разработке вместе со всеми зависимостями этого приложения. Затем вы можете развернуть один или несколько контейнеров из этого образа. Каждый контейнер функционирует как песочница, которая включает все компоненты, необходимые для полной работоспособности приложения.

Образ может быть развернут так часто, как это необходимо, а также совместно использоваться любым количеством контейнеров. Вы создаете контейнеры по мере необходимости, а затем избавляетесь от них, когда вы с ними закончите. Но лучше всего то, что вы можете обновить и повторно развернуть образ в любое время, а затем создать из него новые контейнеры, которые содержат последние изменения.

Вам не нужно выбирать тип контейнера (Windows Server или Hyper-V) до тех пор, пока вы не будете готовы запустить фактический контейнер. Тип контейнера не имеет никакого отношения к тому, как вы собираете ваши образы. Образы хранятся в репозитории и доступны по запросу для разворачивания контейнеров, где и когда они необходимы, будь то контейнеры Windows Server или Hyper-V.

Связь с Docker

Помимо компании, Docker также является проектом с открытым кодом, которая облегчает процесс развертывания и управления контейнерами. Контейнеры Windows теперь являются частью этого проекта, и сообщество Docker интенсивно работает, чтобы полностью интегрировать контейнеры Windows в экосистему Docker. В рамках этой же инициативы Docker предлагает Docker Engine для Windows, и Docker Client для Windows.

Docker Engine обеспечивает функциональность, необходимую для управления Docker окружением. Например, Docker Engine позволяет автоматизировать создание контейнеров из образов. Хотя вы можете создавать образы вручную, Docker Engine предлагает целый ряд преимуществ, т.к. возможность хранения образов как кода, легкого пересоздания этих образов или включения их в цикл непрерывной интеграции в процессе разработки.

Тем не менее, Docker Engine не является частью установки Windows. Вы должны загрузить, установить и настроить его отдельно от Windows. Docker Engine работает как служба Windows. Можно настроить эту службу, используя файл конфигурации или Windows Service Control Manager (SCM). Например, вы можете установить отладку по умолчанию и параметры журнала или настроить, как Docker Engine принимает сетевые запросы. Microsoft рекомендует использовать файл конфигурации, а не SCM, но отмечает, что не каждый параметр конфигурации в файле применим к контейнерам Windows.

Docker Engine по существу делает всю рутинную работу по управлению контейнером за вас, расширяя API, необходимый для клиента Docker для взаимодействия Docker Engine. Клиент представляет собой интерфейс командной строки, который предоставляет набор команд для управления образами и контейнерами. Это те же самые команды, которые позволяют создавать и запускать контейнеры Docker в Linux. Хотя вы и не можете запустить контейнер для Windows на Linux или контейнер Linux на Windows, вы можете использовать один и тот же клиент для управления как Linux и Windows контейнерами, будь то контейнеры Windows Server или Hyper-V.

Как и с Docker Engine, вам необходимо загрузить и установить клиент Docker самостоятельно. Клиент может работать как на Windows 10 или Windows Server 2016. Вам нужно только указать клиенту Docker службу, которой необходимо начать управлять.

Мир Windows

Microsoft и Docker осталось сделать еще много работы, прежде чем контейнеры для Windows будут полностью функциональны, но то, что мы видим уже сейчас представляет собой значительный шаг вперед. Пользователям Windows, наконец, получат возможность пользоваться всеми преимуществами гибкости и переносимости, которые контейнеры предлагали миру Linux на протяжении более десяти лет.

What are Windows containers?

Windows containers provide abstracted, isolated, lightweight and portable operating environments for application development on a single system. These environments make it easier for developers to develop, deploy, run and manage their applications and application dependencies, both on premises and in the cloud.

A container is a logical environment created on a computer where an application can run. Containers and guest applications are abstracted from the host computer’s hardware resources and also logically isolated from other containers. Containers are different than virtual machines (VMs) because they do not rely on a separate hypervisor layer but are supported by the underlying operating system (OS).

Windows containers are useful to package and run enterprise applications. Both Windows OS and Linux OS applications are supported. Since the containers are lightweight and fast, they can be started and stopped quickly, making them ideal for developing applications that can rapidly adapt and scale up or down to changing demand. They are also useful for optimizing infrastructure utilization and density.

Windows containers are suitable for developing any kind of application, including monoliths and microservices. These applications can be developed in any language, including Python, Java and .NET, and can run across both on-premises and cloud environments.

diagram illustrating difference between virtual machines vs. containers

While virtual machines isolate applications, each with a separate OS, containers are an OS-level isolation technology.

How Windows containers work

Containers are created on a container host system that controls how much of its resources can be used by individual containers. For example, it can limit CPU usage to a certain percentage that applications cannot exceed. The host also provides each container with a virtualized namespace that grants access only to the resources the container needs. Such restricted access ensures the container behaves as if it is the only application running on the system.

All containers on a system build on top of and share the same OS kernel, so there’s no need to install a separate OS instance for each container. Each container does not get complete access to the kernel; it only gets an isolated or virtualized view of the system, meaning it can access a virtualized version of the OS file system and registry. Changes to those elements will only affect that container.

The APIs and services an app needs to run are provided by system libraries instead of the kernel. These libraries are files running above the kernel in user mode and packaged into a container or base image. Container images are required to create a container. When the image is deployed to a host system with a compatible container platform such as Docker, the application will run without needing to install or update any other components on the host.

The combination of virtualization and the container image makes containers very portable and self-sufficient. These qualities let developers create, test and deploy applications to production without making changes to the image. They can also interconnect multiple containers to create larger applications using a microservices architecture. These applications are scalable and consist of blocks or functions that communicate with each other via APIs.

diagram illustrating Docker containers stack

A container stack, such as Docker, runs on the host OS — Windows, for example – with host resources.

Microsoft containers ecosystem

It’s easy to develop and deploy containers using Microsoft’s broad container ecosystem. Docker Desktop is part of this ecosystem. It is useful to develop and test Windows- or Linux-based containers on Windows 10.

All apps can be published as container images to the public Docker Hub or to a private Azure Container Registry. Microsoft tools like Visual Studio and Visual Studio Code support containers and technologies like Docker and Kubernetes to develop, test, publish and deploy Windows-based containers.

Containers can be deployed at scale on premises or in the cloud. For deployment in Azure or other clouds, an orchestrator like Azure Kubernetes Service (AKS) is very useful after the container image is pulled from a container registry. For on-premises deployment, AKS on Azure Stack HCI, Azure Stack with the AKS Engine or Azure Stack Hub with OpenShift can be used.

Windows container images

The Windows container image is a file or package that includes the container’s own copy of all user-mode system files. It includes details of the application, data, OS libraries, and all the dependencies and miscellaneous configuration files needed to operate the application. The image can be stored in a local, public or private container repository.

Microsoft provides the following multiple base images that developers can use to build their own Windows container images:

  • Windows. This is the full Windows base image and contains all Windows libraries, APIs and system services except for server roles.
  • Windows Server. This base image contains a full set of Windows APIs and system services; it is equivalent to a full installation of Windows Server.
  • Windows Server Core. This base image is smaller and contains a subset of the APIs, libraries and services included in Windows Server Core. It also includes many server roles, though not all.
  • Nano Server. This is the smallest Windows base image in terms of image size and the number of libraries and services. It includes support for the ASP.NET Core APIs and some server roles.

Windows and Linux container platform

The Windows and Linux container platform includes numerous tools, such as the following:

  • Containerd. Introduced in Windows Server 2019 and Windows 10 version 1809, containerd is a daemon to manage the entire container lifecycle. It can be used to download and unpack the container image and also to execute and supervise containers.
  • Runhcs. Runhcs is a Windows container host and a fork of runc. The runhcs command-line client can be used to run applications packaged according to the Open Container Initiative (OCI) format and runtime specification. It runs on Windows and can run many container types, including Windows and Linux Hyper-V isolation and Windows process containers.
  • HCS. HCS is a C language API with two available wrappers that can interface with HCS and call it from higher-level languages. One wrapper is hcsshim, which is the basis for runhcs. The other is dotnet-computevirtualization, which is written in C#.

Virtual machines vs. Windows containers

VMs and containers are complementary but different technologies. A VM runs a complete OS, including its own kernel, which is why it requires more system resources, such as memory and storage. In contrast, containers build upon the host OS kernel and contain only apps, APIs and services running in user mode. As a result, they use fewer system resources.

Another difference is that it is possible to run any OS inside a VM, while containers necessarily run the same OS and OS version as the host. VMs also provide a stronger security boundary since the VM is completely isolated from the host OS and other VMs. Containers only provide lightweight isolation from the host and other containers. That said, the security of Windows containers can be increased by isolating each container in a lightweight VM using the Hyper-V isolation mode.

Other key differences between VMs and Windows containers include the following:

  • Individual VMs can be deployed by using Windows Admin Center or Microsoft Hyper-V Manager, while individual containers can be deployed with Docker.
  • Multiple VMs can be deployed using PowerShell or System Center Virtual Machine Manager. Multiple containers are best deployed using an orchestrator like AKS, which helps manage containers at scale and provides functionalities for workload scheduling, health monitoring, networking, service discovery and more.
  • For local persistent storage, a single VM uses a virtual hard disk, while a single container node uses Azure Disks.
  • Running VMs can be moved to other VMs in a failover cluster for load balancing. An orchestrator is required to start or stop containers in response to changes in load.
  • VMs use virtual network adapters, while containers use an isolated view of a virtual network adapter and share the host’s firewall with other containers.

Learn more about what Windows admins need to know about VMs and containers and explore virtualization problems and ways to solve them.

This was last updated in July 2023


Continue Reading About Windows containers

  • Adopting containers and preventing container security risks
  • Why Linux containers on Windows is a big deal
  • Container vs. VM security: Which is better?
  • Explore the benefits of containers on bare metal vs. on VMs
  • Containers vs. VMs: What are the key differences?

Dig Deeper on IT operations and infrastructure management

  • containers (container-based virtualization or containerization)

    AlexanderGillis

    By: Alexander Gillis

  • Learn how to use VMware’s OS Optimization Tool

    RobBastiaansen

    By: Rob Bastiaansen

  • An introduction to VMware KVM mode

    RobBastiaansen

    By: Rob Bastiaansen

  • guest OS (guest operating system)

    RahulAwati

    By: Rahul Awati

Microsoft offers many different container models on Windows. If you’re running Windows 10 you’re running several without even realising it: wrapping and isolating all your UWP apps; using thin virtual machines to deliver security; and, if you’re a developer, either Windows or Linux Docker instances.

That layered container model is key to the future of Windows — one that reaches into the upcoming Windows 10X and out into the wider world of public and private clouds, with Docker Windows containers now officially part of Kubernetes. Microsoft is working on shrinking Windows Server to produce lightweight container base images with a more capable Windows.

Windows or Docker?

While the desktop containers are intended to both simplify and secure your desktop applications, providing much-needed isolation for apps installed via appx or MSIX (and in Windows 10X for any other Win32 code), Windows 10’s containers are based on Windows’ own process isolation technology. It’s not the familiar Docker model that we find in our cloud-hosted enterprise applications.

That’s not to say Windows 10 can’t run Docker containers. Microsoft is using Docker’s services to underpin its Windows Server containers. You can build and test code running inside them on Windows PCs, running either Pro or Enterprise builds, and the upcoming 2004 release of Windows 10 brings WSL2 and support for Linux containers running on Windows.

Docker has been developing a new version of its Docker Desktop tools for Windows around WSL2, making it as easy to develop and test Linux containers on Windows 10 as it is to work with Windows’ own containers. With Microsoft positioning Windows as a development platform for Kubernetes and other cloud platforms, first-class Docker support on Windows PCs is essential.

Windows containers in the hybrid cloud

It’s not only Linux containers in the cloud. Windows containers have a place too, hosting .NET and other Windows platforms. Instead of deploying SQL Server or another Windows server application in your cloud services, you can install it in a container and quickly deploy the code as part of a DevOps CI/CD deployment. Modern DevOps treats infrastructures (especially virtual infrastructures) as the end state of a build, so treating component applications in containers as one of many different types of build artifact makes a lot of sense.

What’s important here is not the application, but how it’s orchestrated and managed. That’s where Kubernetes comes in, along with RedHat’s OpenShift Kubernetes service. Recent releases have added support for Windows containers alongside Linux, managing both from the same controller.

While both OpenShift and Kubernetes now support Windows containers, they’re not actually running Windows containers on Linux hosts. There’s no practical reason why they can’t use a similar technique to that used by Docker to run Linux containers on Windows. However, Windows Server’s relatively strict licensing conditions require a Windows licence for each virtual machine instance that was hosting the Windows containers.

Building Windows containers for Windows Server and Azure

Using Windows containers in Kubernetes means building a hybrid infrastructure that mixes Linux and Windows hosts, with Windows containers running on Windows Server-powered worker nodes. Using tools like OpenShift or the Azure Kubernetes Service automates the placement of code on those workers, managing a cross-OS cluster for your application. .NET code can be lifted into a Windows Docker container and deployed via the Azure Container Registry. You can manage those nodes from the same controller as your Linux nodes.

SEE: Serverless computing: A guide for IT leaders (TechRepublic Premium)

There’s no need to learn anything new, if you’re coming to Windows containers from Linux. You’re using familiar Docker tools to build and manage your container images, and then the same Kubernetes tooling as you’d use for a pure Linux application. Mixing and matching Windows and Linux microservices in a single application allows you to take advantage of OS-specific features and to keep the expertise of existing developer teams, even as you’re switching from a traditional monolithic application environment to a modern distributed system.

Microsoft is building a suite of open-source tools to help manage Windows containers, with a GitHub repository for the first one, a logging tool. Improving logging makes sense for a distributed application, where multiple containers interact under the control of Kubernetes operators.

Choosing isolation: process or Hyper-V?

Outside of Kubernetes, Windows containers on Windows Server have two different isolation modes. The first, process isolation, is similar to that used by Linux containers, running multiple images on a host OS, using the same kernel for all the images and the host. Namespaces keep the processes isolated, managing resources appropriately. It’s an approach that’s best used when you know what all the processes running on a server are, ensuring that there’s no risk of information leaking between different container images. The small security risk that comes with a shared kernel is why Microsoft offers a more secure alternative: isolated containers.

Under the hood of Windows Server’s isolated containers is, of course, Hyper-V. Microsoft has been using it to improve the isolation of Docker containers on Windows, using a thin OS layer running on top of Hyper-V to host a Docker container image, keeping performance while ensuring that containers remain fully isolated. While each container is technically a virtual machine with its own kernel, they’re optimised for running container images. Using virtualization in this way adds a layer of hardware isolation between container images, making it harder for information to leak between them and giving you a platform that can host multiple tenant images for you.

It’s easy enough to make and run a Hyper-V container. All you need to do is set the isolation parameter in the Docker command line to ‘hyperv’, which will launch the container using virtualisation to protect it. The default on desktop PCs is to use Hyper-V, for servers it’s to use Docker isolation. As a result, you may prefer to force Hyper-V containers on your Windows Server container hosts.

Microsoft has been working hard to reduce the size of the Hyper-V server image that’s used for Windows containers. It’s gone down from nearly 5GB with Windows Server 1809 and 1903, to half the size at 2.46GB in the upcoming 2004 release. And that’s Windows Server Core, not Nano! Building on Windows Server Core makes sense as it has a larger API surface, reducing the risk of application incompatibility.

With two use cases for its containers, and five different container models, it would seem that Microsoft’s container strategy is ripe for confusion. But that’s not the case. Windows’ own application isolation technologies are managed automatically by the installer, so all you need to consider is whether your server applications run using process isolation or in Hyper-V. And that’s a decision best made by whether you’re running your applications on your own servers in your own data centre, or in the public cloud.

Tags:
Windows, Docker, Linux

Когда вы начнете работать с контейнерами, вы увидите много сходства между контейнером и виртуальной машиной; но, по сути, это два совершенно разных понятия. Контейнеры собираются изменить способ разработки Windows-разработок в следующем году, и они уже лежат в основе большой работы по ускорению процесса доставки. Мы объясним, как использовать функцию Windows Containers.

Введение

Контейнеры Windows революционизируют виртуализацию и процесс DevOps.

С Windows Server 2016 Microsoft представляет новую функцию под названием Windows Containers. Организации, которые обновляют свои серверы до этой новой операционной системы, смогут использовать контейнеры прямо из разработки в производственную среду.

Мы не будем углубляться в концепцию контейнеров, но в этой серии расскажем, как создавать, запускать, конвертировать и управлять вашими контейнерами Windows.

Основы Windows Containers

Прежде чем начать практическую сторону Windows Containers, мы должны вкратце осветить основы этой новой функции.

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

Виртуальные машины против контейнеров

Виртуальная машина является автономной и имеет собственную операционную систему, собственные приложения и собственные ресурсы (память, процессор и т. д.). Следующая схема показывает три виртуальных машины, размещенных на одном и том же физическом узле. Каждая виртуальная машина использует свою собственную ОС, библиотеки и т. Д. В результате они занимают значительное количество памяти.

Архитектура виртуальных машин

Довольно часто разработчикам приходится очень быстро тестировать приложения с разными версиями. Затем они должны попросить команду IT Ops развернуть одну или несколько машин (виртуальных или физических): это трудоемкий процесс. VM также потребляют значительные ресурсы, такие как память и пространство для хранения. Вот почему контейнеры удивительно полезны для процесса DevOps:

Архитектура контейнеров

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

Таким образом, преимущества контейнеров Windows заключаются в следующем:

  • Когда вы развертываете контейнер в рабочей среде, процесс отката очень прост. Вам просто нужно изменить сценарий развертывания и переустановить образ контейнера. Представьте себе процесс отката с виртуальными машинами? Вы должны перестроить всю машину (или вернуться к предыдущему состоянию или резервной копии).
  • Время запуска для контейнера Windows короче, чем у виртуальной машины.
  • Компактность использования облачных сценариев

Наконец, философия контейнера — это «одна услуга на контейнер»,

Windows Server Containers против Hyper-V Containers

Microsoft включает два разных типа контейнера. Первый тип основан на образовании Windows Server Core и называется контейнером Windows Server. Второй называется контейнером Hyper-V и основана на образовании Windows Nano Server. Контейнеры Hyper-V расширяют изоляцию, предоставляемую контейнерами Windows Server, запустив каждый контейнер в высоко оптимизированной виртуальной машине, чтобы обеспечить полную безопасную изоляцию. Ядро хоста контейнера не используется совместно с другими контейнерами Hyper-V. Если весь код, запущенный на хосте, надежен, то изоляция, предоставляемая контейнерами Windows, скорее всего, будет адекватной. Но если мы не доверяем коду, то контейнеры Hyper-V обеспечивают тот же уровень изоляции, что и виртуальные машины, но со многими преимуществами стандартных контейнеров.

Обратите внимание, что контейнеры Hyper-V управляются только Docker, а виртуальные машины Hyper-V управляются традиционными инструментами, такими как Hyper-V Manager. На практике загрузка Hyper-V контейнеров занимает больше времени, чем контейнеры Windows Server, но они намного быстрее, чем виртуальная машина с полной ОС (даже на Nano Server).

Docker

В октябре 2014 года Microsoft Corp и Docker объявили о стратегическом партнерстве, которое обеспечит гибкость, переносимость и безопасность платформы Docker для Windows Server.

Контейнеры Windows Server 2016, работающие от Docker Engine

Необходимо понимать, что Windows Server 2016 не может запускать контейнеры Linux в формате Docker, а только контейнеры Windows. Зачем? Поскольку для Linux-контейнеров требуются API-интерфейсы Linux из ядра-хозяина, а для контейнеров Windows Server требуются API-интерфейсы Windows для ядра Windows-хоста.

Однако процесс управления контейнерами Linux и Windows строго идентичен. Следующая схема описывает платформу Docker:

Платформа Docker

Ниже приведен краткий обзор жаргонов Windows Containers с их значением:

  • Container Host: физическая или виртуальная компьютерная система, настроенная с использованием функции Windows Containers
  • Container Image: Изображение контейнера содержит базовую операционную систему, приложение и все зависимости приложения, которые необходимы для быстрого развертывания контейнера.
  • Container OS Image: Изображение операционной системы контейнера — это среда операционной системы.
  • Container Registry: изображения контейнеров хранятся в реестре контейнеров и могут быть загружены по требованию. Это место, где публикуются изображения контейнеров. Реестр может быть удаленным или локальным.
  • Docker Engine: Это ядро ​​платформы Docker. Облегченное время выполнения контейнера, которое создает и запускает ваш контейнер.
  • Docker file: файлы Docker используются разработчиками для создания и автоматизации создания изображений контейнеров. С файлом Docker демон Docker может автоматически создавать образ контейнера.

Docker предоставляет центральный репозиторий, называемый Docker Hub (https://hub.docker.com/), общедоступный реестр контейнерных приложений, поддерживаемый Docker. Контейнерные изображения могут быть опубликованы непосредственно в этом репозитории для совместного использования с сообществом Docker. На Docker Hub уже много изображений. Например:

  • SQL 
  •  WordPress 
  • IIS 
  •  …

Вы можете запустить частный репозиторий локально. Посредством этого URL-адреса Microsoft имеет собственный публичный и официальный репозиторий: https://hub.docker.com/u/microsoft/

Контейнеры Windows на практике

Перед развертыванием контейнеров Windows вы должны подготовить свою среду с некоторыми предварительными условиями. Для этого вы можете использовать физическую или виртуальную машину, это зависит от вас. В нашем случае мы будем использовать виртуальную машину со следующими характеристиками:

  • Система под управлением Windows Server 2016 (или Windows 10). Это самая важная предпосылка. Советуем вам работать с версией Datacenter из-за лицензирования (больше информации в конце статьи). Вы можете использовать Windows Server Core для своего контейнера, а не версию Windows, которая включает полный пользовательский интерфейс. 
  • Разрешения администратора на хосте контейнера 
  • Минимальное свободное пространство для хранения изображений и сценариев развертывания 
  • Ваш сервер должен быть современным

Хорошо, давайте начнем с установки функции Windows Containers на хосте контейнера. Для выполнения этой задачи запустите следующую команду PowerShell:

PS C:\Users\Administrator> Install-WindowsFeature Containers

Success Restart Needed Exit Code      Feature Result

      

True    Yes            SuccessRest... {Containers}

WARNING: You must restart this server to finish the installation process.

Чтобы применить изменения с помощью командлета Restart-Computer, необходимо перезапустить: 

PS C:\Users\Administrator> Restart-Computer

Затем проверьте, что новая функция включена:

PS C:\Users\Administrator> Get-WindowsFeature containers

Display Name       Name                       Install State

                             

[X] Containers     Containers                     Installed

Контейнеры Windows тесно связаны с Docker; вы должны установить Docker Engine на хост контейнера. Для достижения этой цели у вас есть две возможности: 

Первым из них является развертывание Docker из репозитория PSGallery: 

PS C:\Users\Administrator> Install-Module -Name DockerMsftProvider -Repository PSGallery -Force

NuGet provider is required to continue

PowerShellGet requires NuGet provider version ‘2.8.5.201’ or newer to interact with NuGet-based repositories. The NuGet

provider must be available in ‘C:\Program Files\PackageManagement\ProviderAssemblies’ or

‘C:\Users\Administrator\AppData\Local\PackageManagement\ProviderAssemblies’. You can also install the NuGet provider by

running ‘Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force’. Do you want PowerShellGet to install

and import the NuGet provider now?

[Y] Yes  [N] No  [S] Suspend  [?] Help (default is «Y»):

PS C:\Users\Administrator> Install-Package -Name docker -ProviderName DockerMsftProvider

The package(s) come(s) from a package source that is not marked as trusted.

Are you sure you want to install software from ‘DockerDefault’?

[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is «N»): Y

Install-Package : KB3176936 or later is required for docker to work

At line:1 char:1

+ Install-Package -Name docker -ProviderName DockerMsftProvider

+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    + CategoryInfo          : InvalidOperation: (Microsoft.Power....InstallPackage:InstallPackage) [Install-Package],

   Exception

    + FullyQualifiedErrorId : RequiredWindowsUpdateNotInstalled,Install-Package,Microsoft.PowerShell.PackageManagement

   .Cmdlets.InstallPackage

Докер для Windows Server 2016 требует обновления «KB3176936». Его можно загрузить с веб-сайта Центра обновления Windows, а затем установить вручную: 

http://www.catalog.update.microsoft.com/search.aspx?q.. 

Или вы можете выполнить эту задачу с помощью утилиты sconfig. Затем выберите число 6: 

===============================================================================

                         Server Configuration

===============================================================================

1) Domain/Workgroup:                    Domain:  get-cmd.Local

2) Computer Name:                       SRV1

3) Add Local Administrator

4) Configure Remote Management          Enabled

5) Windows Update Settings:             DownloadOnly

6) Download and Install Updates

7) Remote Desktop:                      Enabled (more secure clients only)

8) Network Settings

9) Date and Time

10) Telemetry settings                  Basic

11) Windows Activation

12) Log Off User

13) Restart Server

14) Shut Down Server

15) Exit to Command Line

Windows загрузит и установит обновления: 

Microsoft (R) Windows Script Host Version 5.812

Copyright (C) Microsoft Corporation. All rights reserved.

Search for for (A)ll updates or (R)ecommended updates only? a

Searching for all applicable updates...

Downloading updates...

Второй способ — установить версию Docker для разработки, чтобы иметь новейшие функции. Вы должны скачать Docker прямо с официального сайта. Используйте командлет Invoke-WebRequest: 

PS > Invoke-WebRequest «https://master.dockerproject.org/windows/amd64/docker-1.14.0-dev.zip» -OutFile «$env:TEMP\docker.zip» UseBasicParsing

Затем извлеките архив с помощью командлета Expand-Archive: 

PS > Expand-Archive -Path «$env:TEMP\docker.zip» -DestinationPath $env:ProgramFiles

Теперь вы можете создать переменную окружения: 

PS > $env:path += «;$env:ProgramFiles\Docker»

PS > $existingMachinePath = [Environment]::GetEnvironmentVariable(«Path»,[System.EnvironmentVariableTarget]::Machine)

PS > [Environment]::SetEnvironmentVariable(«Path», $existingMachinePath + «;$env:ProgramFiles\Docker», [EnvironmentVariableTarget]::Machine)

Чтобы закончить, установите Docker в качестве службы Windows. Итак, запустите следующую команду для регистрации файла dockerd.exe:

PS > dockerd register-service

После установки сервис может быть запущен: 

PS > Start-Service Docker

WARNING: Waiting for service ‘Docker Engine (Docker)’ to start...

PS > Get-Service -name «docker*»

Status   Name               DisplayName

                 

Running  docker             Docker Engine

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

PS C:\> docker info

Containers: 0

Running: 0

Paused: 0

Stopped: 0

Images: 0

Server Version: 1.14.0-dev

Storage Driver: windowsfilter

Windows:

Logging Driver: json-file

Plugins:

Volume: local

Network: l2bridge l2tunnel nat null overlay transparent

Swarm: inactive

Default Isolation: process

Kernel Version: 10.0 14393 (14393.0.amd64fre.rs1_release.160715-1616)

Operating System: Windows Server 2016 Datacenter

OSType: windows

Architecture: x86_64

CPUs: 1

Total Memory: 1.933 GiB

Name: SRV1

ID: VB3B:IGYN:GEFL:6ML7:OQJM:GMCJ:HDNU:Z57W:SWYI:Z2I3:WZKG:O2L4

Docker Root Dir: C:\ProgramData\docker

Debug Mode (client): false

Debug Mode (server): false

Registry: https://index.docker.io/v1/

Experimental: false

Insecure Registries:

127.0.0.0/8

Live Restore Enabled: false

Итак, хост контейнера запущен и работает, поэтому мы можем развернуть наш первый Windows Container! В первом примере мы будем развертывать контейнер IIS, запускаем следующую команду: 

PS > Docker run -d -p 8080:80 name iis microsoft/iis

Unable to find image ‘microsoft/iis:latest’ locally

latest: Pulling from microsoft/iis

c480435b7cba: Downloading [==>                                                ] 220.1 MB/4.175 GB

2acd7c473906: Downloading [=============>                                     ] 240.1 MB/922.1 MB

a837699b27ea: Download complete

e4e8167eafc5: Download complete

0344b06e0e62: Download complete

Ниже приведен синтаксис команды Docker: 

PS > docker run PUBLIC_PORT:PRIVATE_CONTAINER_PORT CONTAINER_NAME IMAGE

Контейнеры используют концепцию PAT (Port Address Translation). Это означает, что вы должны открывать порты контейнера через хост контейнера. В нашем примере Docker свяжет контейнер порта номер 80 с номером 8080 контейнера порта. Затем, когда мы попытаемся открыть веб-сайт IIS, расположенный внутри контейнера, я буду использовать открытый порт 8080. 

Параметр «Name» добавляет дружественное имя в контейнер. Это не обязательно, но может быть полезно для последующего управления вашими контейнерами. 

Наконец, вы должны указать имя образа контейнера. Здесь мы выбираем образ IIS, предоставленный Microsoft. 

Когда я запускаю команду, Windows проверяет, доступно ли изображение локально (на хосте контейнера). Если нет, то Docker извлекает изображение из концентратора Docker.

PS > Docker run -d -p 8080:80 name iis microsoft/iis

Unable to find image ‘microsoft/iis:latest’ locally

Когда это будет сделано, ваш Windows Container будет запущен. Наш хост контейнера имеет следующий IP-адрес: 192.168.0.132, поэтому мой веб-сайт IIS доступен с 192.168.0.132:8080 

Контейнер IIS 

Дальнейшая работа

Image2Docker 

Допустим, у вас есть сервер, который был любовно собран вручную и который вы хотите контейнеризировать? Ну, вы можете использовать модуль PowerShell «Image2Docker», доступный в GitHub: https://github.com/docker/communitytools-image2docker.., который передает рабочие нагрузки приложений Windows из виртуальных машин на изображения Docker. Таким образом, вы можете легко конвертировать службы Windows в контейнеры Windows, такие как: сайты IIS, DNS, DHCP, … 

Лицензирование 

Официальный сайт содержит относительно небольшую информацию о лицензировании, но в соответствии с Техническим паспортом лицензирования Windows Server 2016 Standard Edition предоставляет права на до 2 контейнеров Hyper-V, когда все физические ядра на сервере лицензированы и контейнеры Windows Server неограничены для обоих выпусков.

Заключение

Контейнеры Windows уже меняют способы организации систем и предоставления услуг. Контейнеры начинают играть все более важную роль для разработчиков и операционных систем, чтобы не тратить слишком много времени на развертывание приложений. 

Контейнерные технологии не новы в мире Linux, но для Microsoft это революция. Важно срочно найти время, чтобы понять все аспекты реализации контейнеров в вашей организации.

В этой статье мы видели, как развернуть наш первый контейнер Windows. Вы скоро заметите, что контейнеры замечательны для разработчиков и администраторов, поскольку контейнеризация обеспечивает большую гибкость в использовании и упрощает развертывание. Есть еще много вещей, которые нужно сказать о контейнерах, поэтому в следующих статьях мы объясним: 

  • Какие нужны команды Docker для начала работы с Docker, 
  • Как найти и загрузить изображения контейнеров, 
  • Как использовать контейнеры Hyper-V, 
  • Как создать собственное изображение Контейнера, 
  • Как конвертировать службы Windows для работы в контейнере Windows

Надеюсь, что эта статья поможет вам расширить свои знания о контейнерах Windows.

When you begin to work with containers, you will notice many similarities between a container and a virtual machine; but, in fact, these are two quite different concepts. Containers are going to change the way that we do Windows-based development work in the coming year, and they already underpin much of the devops work of speeding the delivery process. Nicolas Prigent explains how to use the Windows Containers feature.

  • First Part – The basics: the basic principles of how container virtualization is implemented in Windows Server 2016 operating system.
  • Second part – Up and Running: creating and managing Windows Server Containers using Docker.
  • Third part – Into your Stride Working with Windows Containers and Docker
  • Fourth part — Save the Container Data

Introduction

Windows containers will revolutionize virtualization and the DevOps process.

With Windows Server 2016, Microsoft introduces the new feature called Windows Containers. Organizations that upgrade their servers to this new operating system will then be able to use containers right through from development to the production environment.

Robert Sheldon wrote a great article about Windows containers on Simple Talk: https://www.simple-talk.com/cloud/platform-as-a-service/windows-containers-and-docker/. We will not dig deep once again into the concept of containers, but I will explain in this series how to create, run, convert and manage your Windows Containers.

Windows Containers Fundamentals

Before starting with the practical side of Windows Containers, I ought to quickly cover the basics about this new feature.

Containers wrap software up within in a complete file system that contains everything it needs to run: code, runtime, system tools and system libraries. This guarantees that it will always run the same, regardless of the environment it is running within. To achieve this goal, Windows uses namespace isolation, resource control, and process-isolation technologies to restrict the files, network ports, and running processes that each container can access, so that applications running in containers can’t interact or see other applications running in the host OS or in other containers.

Virtual Machines Vs Containers

A Virtual machine is standalone and has its own operating system, its own applications and its own resources (memory, CPU and so on). The following schema shows three VMs hosted on the same physical host. Each virtual machine uses its own OS, libraries, etc. In consequence, they occupy significant amounts of memory.

VMs architecture

Quite often, developers need to test applications with different versions very quickly. Then they must ask to the IT Ops team to deploy one or many machines (Virtual or Physical): It is a time consuming process. VMs also consume considerable resources such as memory and storage space. That’s the reason why containers are amazingly useful for the DevOps process:

Containers architecture

Containers, in contrast, do not contain any operating system, so they take up fewer resources than virtual machines on the physical host. Containers simply share the host operating system, including the kernel and libraries, so they don’t need to boot a full OS.

In summary, the benefits of Windows containers are that:

  • When you deploy a container in a production environment, the rollback process is very simple. You just need to modify the deployment script and redeploy the Container image. Just imagine the rollback process with virtual machines? Well, you must rebuild the entire machine (or revert to the previous snapshot/backup).
  • Startup time for a Windows container is faster than a VM.
  • The small footprint benefits cloud-based scenarios

To finish, the container philosophy is “one service per container”

Windows Server Containers Vs Hyper-V Containers

Microsoft includes two different types of container. The first type is based on the Windows Server Core image and is called a Windows Server Container. The second one is called a Hyper-V Container and is based on the Windows Nano Server image. Hyper-V Containers expand on the isolation that is provided by Windows Server Containers by running each container in a highly-optimized virtual machine, so that they provide a full secure isolation. The kernel of the container host is not shared with other Hyper-V Containers. If all the code running on a host is trusted, then the isolation provided by Windows Containers is likely to be adequate. But if we don’t trust the code, then Hyper-V Containers provide the same level of isolation as virtual machines, but with many of the benefits of standard containers.

Please note that Hyper-V containers are only managed by Docker, while Hyper-V Virtual Machines are managed by traditional tools such as Hyper-V Manager. In practice, booting Hyper-V containers takes longer than Windows Server Containers but both are much faster than a VM with a full OS (even on Nano Server).

Docker

In October 2014, Microsoft Corp and Docker announced a strategic partnership to bring the agility, portability, and security benefits of the Docker platform to Windows Server.

Windows Server 2016 Containers, powered by Docker Engine

It is essential to understand that Windows Server 2016 can’t run Linux containers in Docker format but only Windows containers. Why? Because Linux containers require the Linux APIs from the host kernel and Windows Server Containers require the Windows APIs of a host Windows kernel.

However, the process of managing Linux and Windows containers are strictly identical. The following schema describe the Docker platform:

Docker Platform

Here is a summary of Windows Containers jargon with their meaning:

  • Container Host: Physical or Virtual computer system configured with the Windows Container feature.
  • Container Image: A container image contains the base operating system, application, and all the application dependencies that are needed to quickly deploy a container.
  • Container OS Image: The container OS image is the operating system environment.
  • Container Registry: Container images are stored in a container registry, and can be downloaded on demand. It is a place where container images are published. A registry can be remote or on-premises.
  • Docker Engine: It is the core of the Docker platform. It is a lightweight container runtime that builds and runs your container.
  • Docker file: Docker files are used by developers to build and automate the creation of container images. With a Docker file, the Docker daemon can automatically build a container image.

Docker provides a central repository called Docker Hub (https://hub.docker.com/), the public containerized-application registry that Docker maintains. Container Images can be published directly on this repository to be shared with the Docker community. There are already many images hosted on the Docker Hub. For example:

  • SQL
  • WordPress
  • IIS

You can run a private repository on-premise. Microsoft has its own public and official repository available via this URL: https://hub.docker.com/u/microsoft/

Docker Hub

Windows Containers in practice

Before deploying Windows Containers, you must prepare your environment with some prerequisites. To do that, you can use a physical or virtual machine, it’s up to you. In my case, I use a VM with the following characteristics:

  • A system running Windows Server 2016 (or Windows 10). It is the most important prerequisite. I advise you to work with the Datacenter version because of licensing (more information at the end of the article). You can choose to use Windows Server Core for your container host as opposed to the version of windows which includes a full UI.
  • Administrator permissions on the container host
  • Minimum free drive space to store images and deployment scripts
  • Your server must be up-to-date

OK, let’s start by installing the Windows Containers feature on the container host. To perform this task, run the following PowerShell command:

PS C:\Users\Administrator> Install-WindowsFeature Containers

Success Restart Needed Exit Code      Feature Result

      

True    Yes            SuccessRest... {Containers}

WARNING: You must restart this server to finish the installation process.

You must restart to apply changes via the Restart-Computer cmdlet:

PS C:\Users\Administrator> Restart-Computer

Then check that the new feature is enabled:

PS C:\Users\Administrator> Get-WindowsFeature containers

Display Name       Name                       Install State

                             

[X] Containers     Containers                     Installed

Windows containers being intimately linked to Docker; you must install Docker Engine on the container host. To achieve this goal, you have two possibilities:

The first one is to deploy Docker from the PSGallery repository:

PS C:\Users\Administrator> Install-Module -Name DockerMsftProvider -Repository PSGallery -Force

NuGet provider is required to continue

PowerShellGet requires NuGet provider version ‘2.8.5.201’ or newer to interact with NuGet-based repositories. The NuGet

provider must be available in ‘C:\Program Files\PackageManagement\ProviderAssemblies’ or

‘C:\Users\Administrator\AppData\Local\PackageManagement\ProviderAssemblies’. You can also install the NuGet provider by

running ‘Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force’. Do you want PowerShellGet to install

and import the NuGet provider now?

[Y] Yes  [N] No  [S] Suspend  [?] Help (default is «Y»):

If you need more details about managing packages with PowerShell, I forward you to this article: https://www.simple-talk.com/sysadmin/powershell/managing-packages-using-windows-powershell/

PS C:\Users\Administrator> Install-Package -Name docker -ProviderName DockerMsftProvider

The package(s) come(s) from a package source that is not marked as trusted.

Are you sure you want to install software from ‘DockerDefault’?

[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is «N»): Y

Install-Package : KB3176936 or later is required for docker to work

At line:1 char:1

+ Install-Package -Name docker -ProviderName DockerMsftProvider

+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    + CategoryInfo          : InvalidOperation: (Microsoft.Power....InstallPackage:InstallPackage) [Install-Package],

   Exception

    + FullyQualifiedErrorId : RequiredWindowsUpdateNotInstalled,Install-Package,Microsoft.PowerShell.PackageManagement

   .Cmdlets.InstallPackage

Docker for Windows Server 2016 requires update “KB3176936”. You can download it from the Windows Update Website and then install manually:

http://www.catalog.update.microsoft.com/search.aspx?q=kb3176936

Or you can perform this task using sconfig utility. Then, choose the number 6:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

===============================================================================

                         Server Configuration

===============================================================================

1) Domain/Workgroup:                    Domain:  get-cmd.Local

2) Computer Name:                       SRV1

3) Add Local Administrator

4) Configure Remote Management          Enabled

5) Windows Update Settings:             DownloadOnly

6) Download and Install Updates

7) Remote Desktop:                      Enabled (more secure clients only)

8) Network Settings

9) Date and Time

10) Telemetry settings                  Basic

11) Windows Activation

12) Log Off User

13) Restart Server

14) Shut Down Server

15) Exit to Command Line

Windows will download and install updates:

Microsoft (R) Windows Script Host Version 5.812

Copyright (C) Microsoft Corporation. All rights reserved.

Search for for (A)ll updates or (R)ecommended updates only? a

Searching for all applicable updates...

Downloading updates...

The second way is to install the development Docker version, in order to have the latest features. You must download Docker directly from the official website. Use the Invoke-WebRequest cmdlet:

PS > Invoke-WebRequest «https://master.dockerproject.org/windows/amd64/docker-1.14.0-dev.zip» -OutFile «$env:TEMP\docker.zip» UseBasicParsing

Next, extract the archive via the Expand-Archive cmdlet:

PS > Expand-Archive -Path «$env:TEMP\docker.zip» -DestinationPath $env:ProgramFiles

Now, you can create an environment variable:

PS > $env:path += «;$env:ProgramFiles\Docker»

PS > $existingMachinePath = [Environment]::GetEnvironmentVariable(«Path»,[System.EnvironmentVariableTarget]::Machine)

PS > [Environment]::SetEnvironmentVariable(«Path», $existingMachinePath + «;$env:ProgramFiles\Docker», [EnvironmentVariableTarget]::Machine)

To finish, install Docker as a Windows service. So run the following command to register dockerd.exe:

PS > dockerd register-service

Once installed, the service can be started:

PS > Start-Service Docker

WARNING: Waiting for service ‘Docker Engine (Docker)’ to start...

PS > Get-Service -name «docker*»

Status   Name               DisplayName

                 

Running  docker             Docker Engine

To display Docker information, run the following:

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

31

PS C:\> docker info

Containers: 0

Running: 0

Paused: 0

Stopped: 0

Images: 0

Server Version: 1.14.0-dev

Storage Driver: windowsfilter

Windows:

Logging Driver: json-file

Plugins:

Volume: local

Network: l2bridge l2tunnel nat null overlay transparent

Swarm: inactive

Default Isolation: process

Kernel Version: 10.0 14393 (14393.0.amd64fre.rs1_release.160715-1616)

Operating System: Windows Server 2016 Datacenter

OSType: windows

Architecture: x86_64

CPUs: 1

Total Memory: 1.933 GiB

Name: SRV1

ID: VB3B:IGYN:GEFL:6ML7:OQJM:GMCJ:HDNU:Z57W:SWYI:Z2I3:WZKG:O2L4

Docker Root Dir: C:\ProgramData\docker

Debug Mode (client): false

Debug Mode (server): false

Registry: https://index.docker.io/v1/

Experimental: false

Insecure Registries:

127.0.0.0/8

Live Restore Enabled: false

Ok now, the container host is up and running, so we can deploy our first Windows container! For the first example, we will deploy a IIS container, run the following command:

PS > Docker run -d -p 8080:80 name iis microsoft/iis

Unable to find image ‘microsoft/iis:latest’ locally

latest: Pulling from microsoft/iis

c480435b7cba: Downloading [==>                                                ] 220.1 MB/4.175 GB

2acd7c473906: Downloading [=============>                                     ] 240.1 MB/922.1 MB

a837699b27ea: Download complete

e4e8167eafc5: Download complete

0344b06e0e62: Download complete

Below is the syntax of the Docker command:

PS > docker run PUBLIC_PORT:PRIVATE_CONTAINER_PORT CONTAINER_NAME IMAGE

Containers use the PAT concept (Port Address Translation). It means that you must expose container ports through the container host. In my example, Docker will bind the port container number 80 to the port container host number 8080. Then, when I will try to open the IIS website located inside the container, I will use the public port 8080.

The « Name » parameter adds a friendly name to the container. It is not mandatory but it can be useful to manage your containers later.

Finally, you must specify the container image name. Here, I choose the IIS image provided by Microsoft.

When I run the command, Windows checks if the image is available locally (on the container host). If not, then Docker retrieves the image from the Docker hub.

PS > Docker run -d -p 8080:80 name iis microsoft/iis

Unable to find image ‘microsoft/iis:latest’ locally

When it’s done, your Windows Container is running. My container host has the following IP Address: 192.168.0.132, so my IIS website is available from 192.168.0.132:8080

IIS Container

To Go Further

Image2Docker

Let’s say you have a server that has been lovingly hand-crafted that you want to containerize? Well, you can use the “Image2Docker” PowerShell module available on GitHub: https://github.com/docker/communitytools-image2docker-win which ports existing Windows application workloads from virtual machines to Docker images. So you can easily convert Windows Services to Windows Containers such as: IIS websites, DNS, DHCP, …

Licensing

Official website contains relatively little information about licensing, but according to the Windows Server 2016 Licensing Datasheet, Standard Edition provides rights for up to 2 Hyper-V containers when all physical cores in the server are licensed and unlimited Windows Server containers for both editions.

Conclusion

Windows containers are already changing the way organizations build systems and deliver services. Containers are increasingly important to ensure that developers and Ops don’t spend too much time to deploy applications.

Container technology is not new in Linux world, but for Microsoft, it’s a revolution. It is important to urgently find the time to understand the ins and outs of implementing containers in your organization.

We have seen, in this article, how to deploy our first Windows container. You will soon notice that Containers are wonderful for Developers and Administrators because containerization allows great flexibility of use and will simplify your deployments. There are still many things to be said about Containers, so in the next articles, I will explain:

  • The Docker commands to get started with Docker,
  • How to find and download container images,
  • How to use Hyper-V Containers,
  • How to create your own Container image,
  • How to convert Windows services to run in a Windows Container,

I hope that this article has helped you to increase your knowledge about Windows Containers.

  • Copy trance heic for windows скачать бесплатно
  • Contacts backup скачать для windows phone
  • Connectify скачать на русском языке для windows 7 скачать бесплатно на русском
  • Connectify hotspot скачать бесплатно на русском языке для windows 7
  • Copy files from windows to ubuntu