Windows and containers
Containers are a technology for packaging and running Windows and Linux applications across diverse environments on-premises and in the cloud. Containers provide a lightweight, isolated environment that makes apps easier to develop, deploy, and manage. Containers start and stop quickly, making them ideal for apps that need to rapidly adapt to changing demand. The lightweight nature of containers also make them a useful tool for increasing the density and utilization of your infrastructure.
To view a roadmap of planned and currently available features, see the Windows Server containers roadmap.
The Microsoft container ecosystem
Microsoft provides a number of tools and platforms to help you develop and deploy apps in containers:
Run Windows-based or Linux-based containers on Windows 10 for development and testing using Docker Desktop, which makes use of containers functionality built-in to Windows. You can also run containers natively on Windows Server.
Develop, test, publish, and deploy Windows-based containers using the powerful container support in Visual Studio and Visual Studio Code, which include support for Docker, Docker Compose, Kubernetes, Helm, and other useful technologies.
Publish your apps as container images to the public DockerHub for others to use, or to a private Azure Container Registry for your org’s own development and deployment, pushing and pulling directly from within Visual Studio and Visual Studio Code.
Deploy containers at scale on Azure or other clouds:
- Pull your app (container image) from a container registry, such as the Azure Container Registry, and then deploy and manage it at scale using an orchestrator such as Azure Kubernetes Service (AKS) or Azure Service Fabric.
- Azure Kubernetes Service deploys containers to Azure virtual machines and manages them at scale, whether that’s dozens of containers, hundreds, or even thousands. The Azure virtual machines run either a customized Windows Server image (if you’re deploying a Windows-based app), or a customized Ubuntu Linux image (if you’re deploying a Linux-based app).
Deploy containers on-premises by using Azure Stack with the AKS Engine (in preview with Linux containers) or Azure Stack with OpenShift. You can also set up Kubernetes yourself on Windows Server (see Kubernetes on Windows), and we’re working on support for running Windows containers on RedHat OpenShift Container Platform as well.
How containers work
A container is an isolated, lightweight silo for running an application on the host operating system. Containers build on top of the host operating system’s kernel (which can be thought of as the buried plumbing of the operating system), as shown in this diagram.
While a container shares the host operating system’s kernel, the container doesn’t get unfettered access to it. Instead, the container gets an isolated–and in some cases virtualized–view of the system. For example, a container can access a virtualized version of the file system and registry, but any changes affect only the container and are discarded when it stops. To save data, the container can mount persistent storage such as an Azure Disk or a file share (including Azure Files).
A container builds on top of the kernel, but the kernel doesn’t provide all of the APIs and services an app needs to run–most of these are provided by system files (libraries) that run above the kernel in user mode. Because a container is isolated from the host’s user mode environment, the container needs its own copy of these user mode system files, which are packaged into something known as a base image. The base image serves as the foundational layer upon which your container is built, providing it with operating system services not provided by the kernel. But we’ll talk more about container images later.
Containers vs. virtual machines
In contrast to a container, a virtual machine (VMs) runs a complete operating system–including its own kernel–as shown in this diagram.
Containers and virtual machines each have their uses–in fact, many deployments of containers use virtual machines as the host operating system rather than running directly on the hardware, especially when running containers in the cloud.
For more details on the similarities and differences of these complementary technologies, see Containers vs. virtual machines.
Container images
All containers are created from container images. Container images are a bundle of files organized into a stack of layers that reside on your local machine or in a remote container registry. The container image consists of the user mode operating system files needed to support your app, your app, any runtimes or dependencies of your app, and any other miscellaneous configuration file your app needs to run properly.
Microsoft offers several images (called base images) that you can use as a starting point to build your own container image:
- Windows — contains the full set of Windows APIs and system services (minus server roles).
- Windows Server Core — a smaller image that contains a subset of the Windows Server APIs–namely the full .NET framework. It also includes most server roles, though sadly to few, not Fax Server.
- Nano Server — the smallest Windows Server image, with support for the .NET Core APIs and some server roles.
- Windows 10 IoT Core — a version of Windows used by hardware manufacturers for small Internet of Things devices that run ARM or x86/x64 processors.
As mentioned earlier, container images are composed of a series of layers. Each layer contains a set of files that, when overlaid together, represent your container image. Because of the layered nature of containers, you don’t have to always target a base image to build a Windows container. Instead, you could target another image that already carries the framework you want. For example, the .NET team publishes a .NET core image that carries the .NET core runtime. It saves users from needing to duplicate the process of installing .NET core–instead they can reuse the layers of this container image. The .NET core image itself is built based upon Nano Server.
Container users
Containers for developers
Containers help developers build and ship higher-quality apps, faster. With containers, developers can create a container image that deploys in seconds, identically across environments. Containers act as an easy mechanism to share code across teams and to bootstrap a development environment without impacting your host filesystem.
Containers are portable and versatile, can run apps written in any language, and they’re compatible with any machine running Windows 10, version 1607 or later, or Windows Server 2016 or later. Developers can create and test a container locally on their laptop or desktop, and then deploy that same container image to their company’s private cloud, public cloud, or service provider. The natural agility of containers supports modern app development patterns in large-scale, virtualized cloud environments.
Containers for IT professionals
Containers help admins create infrastructure that’s easier to update and maintain, and that more fully utilizes hardware resources. IT professionals can use containers to provide standardized environments for their development, QA, and production teams. By using containers, systems administrators abstract away differences in operating system installations and the underlying infrastructure.
Container orchestration
Orchestrators are a critical piece of infrastructure when setting up a container-based environment. While you can manage a few containers manually using Docker and Windows, apps often make use of five, ten, or even hundreds of containers, which is where orchestrators come in.
Container orchestrators were built to help manage containers at scale and in production. Orchestrators provide functionality for:
- Deploying at scale
- Workload scheduling
- Health monitoring
- Failing over when a node fails
- Scaling up or down
- Networking
- Service discovery
- Coordinating app upgrades
- Cluster node affinity
There are many different orchestrators that you can use with Windows containers; here are the options Microsoft provides:
- Azure Kubernetes Service (AKS) — use a managed Azure Kubernetes service
- Azure Service Fabric — use a managed service
- Azure Stack with the AKS Engine — use Azure Kubernetes Service on-premises
- Kubernetes on Windows — set up Kubernetes yourself on Windows
Try containers on Windows
To get started with containers on Windows Server or Windows 10, see the following:
For help deciding which Azure services are right for your scenario, see Azure container services and Choosing what Azure services to use to host your application.
Windows контейнеры и Docker
Начиная с 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 имеет много общего с его аналогом в Linux. Оба обеспечивают изолированную среду для запуска приложений. И там и там контейнеры используют передовые технологии изоляции для обеспечения портативной, но одновременно ограниченной среды, которая включает в себя практически все, чтобы приложение могло быть полностью функциональным.
Контейнер очень похож на виртуальную машину (ВМ) и часто рассматривается как отдельный тип виртуализации, но это два совершенно разные понятия. Да, каждый работает под управлением операционной системы (ОС), предоставляет внутри себя локальную файловую систему и может быть доступен по сети так же как физический компьютер. Тем не менее, при использовании ВМ вы имеете дело с полной и независимой ОС вместе с виртуальными драйверами устройств, управлением памятью и другими компонентами, которые добавляют к накладные расходы.
Контейнер переиспользует большее количество общих ресурсов хост-системы нежели виртуальная машина, а значит, он более легкий, быстрее разворачивается и проще масштабируется между различными датацентрами. Таким образом, контейнер может предложить более эффективный механизм для инкапсулирования приложения, обеспечивая ему при этом необходимые интерфейсы хост-системы — все из этого приводит к более эффективному использованию ресурсов и улучшению переносимости приложений.
Microsoft планирует предложить два типа контейнеров в Windows Server 2016: контейнер Windows Server и Hyper-V контейнер. Оба типа функционируют одинаковым образом, и могут быть созданы и управляются одинаково. Там, где они различаются — это в уровне изоляции, который каждый из них обеспечивает.
Контейнер Windows Server разделяет ядро с ОС работает на хост-машине, что означает, что все контейнеры, работающие на этой машине, разделяют одно и то же ядро. В то же время, каждый контейнер поддерживает свой собственный вид на операционную систему, реестр, файловую систему, IP-адреса и другие компоненты, сочетая это с изоляцией, предоставляемой каждому контейнеру при помощи процессов, пространства имен и технологий управления ресурсами.
Контейнер Windows Server хорошо подходит для ситуаций, в которых и основная ОС, и приложения в контейнерах лежат в пределах той же зоны доверия, например для приложений, которые охватывают несколько контейнеров или образуют общую службу. Тем не менее, контейнеры Windows Server обсуждаются в связи с их зависимостью от процесса обновления ОС хост-системы, который может осложнить обслуживание и препятствовать процессам. Например, патч примененный к хосту может сломать приложение, работающее в контейнере. Что еще более важно, в таких ситуациях, как многопользовательские среды, модель разделяемого ядра может раскрыть систему для уязвимостей приложений и кросс-контейнерных атак.
Hyper-V контейнер решает эти проблемы, предоставляя виртуальную машину, в которой нужно запустить контейнер Windows. При таком подходе контейнер больше не разделяет ядро хост-машины и не имеет зависимости от патчей ОС этой машины. Конечно, такой подход означает некоторую потерю скорости и эффективности упаковки, которые вы получаете с обычным контейнером в Windows Server, но взамен вы получаете более изолированную и безопасную среду.
Вне зависимости от типа контейнера, который вы используете, теперь у вас есть возможность использовать контейнеры с такими технологиями Windows как .NET или PowerShell, что не было возможно раньше. Контейнер для Windows предоставляет все необходимое для обеспечения работы приложения на любом компьютере под управлением Windows Server 2016, давая вам тот уровень переносимости, который был не доступен на протяжении большей части истории Windows. Вы можете создавать свои контейнеры локально, делать их доступными процессов для тестирования и контроля качества, а затем отправить их в команде, занимающейся продуктивом, без необходимости беспокоиться о сложных установках и конфигурациях на каждом шаге этого пути.