- Развертывание узла контейнера: Windows Server Container host deployment: Windows Server
- Установка Docker Install Docker
- Установка конкретной версии Docker Install a specific version of Docker
- Обновление Docker Update Docker
- Установка базовых образов контейнеров Install base container images
- Windows Server 2019 и более поздних версий Windows Server 2019 and newer
- Windows Server 2016 (версии 1607–1803) Windows Server 2016 (versions 1607-1803)
- Узел с изоляцией Hyper-V Hyper-V isolation host
- Вложенная виртуализация Nested virtualization
- Включение роли Hyper-V Enable the Hyper-V role
- Dockerfile on Windows
- Basic Syntax
- Instructions
- Considerations for using RUN with Windows
- Examples of using RUN with Windows
- Considerations for using COPY with Windows
- Examples of using COPY with Windows
- Considerations for running ADD with Windows
- Examples of using ADD with Windows
- WORKDIR
- Considerations for using WORKDIR with Windows
- Considerations for using CMD with Windows
- Escape character
- PowerShell in Dockerfile
- PowerShell cmdlets
- REST calls
- PowerShell scripts
- Docker build
Развертывание узла контейнера: Windows Server Container host deployment: Windows Server
Чтобы развернуть узел контейнера Windows, нужно выполнить разные действия в зависимости от типа операционной системы виртуальной машины и операционной системы сервера виртуальных машин (виртуальная и физическая). Deploying a Windows container host has different steps depending on the operating system and the host system type (physical or virtual). Этот документ описывает развертывание узла контейнера Windows в Windows Server 2016 или Windows Server Core 2016 в физической или виртуальной системе. This document details deploying a Windows container host to either Windows Server 2016 or Windows Server Core 2016 on a physical or virtual system.
Установка Docker Install Docker
Docker необходим для работы с контейнерами Windows. Docker is required in order to work with Windows containers. Docker состоит из подсистемы Docker Engine и клиента Docker. Docker consists of the Docker Engine and the Docker client.
Для установки Docker будет использоваться модуль PowerShell поставщика OneGet. To install Docker, we’ll use the OneGet provider PowerShell module. Поставщик обеспечит работу контейнеров на компьютере и установит Docker. После этого потребуется перезагрузка. The provider will enable the containers feature on your machine and install Docker, which will require a reboot.
Откройте сеанс PowerShell с повышенными правами и выполните следующие командлеты. Open an elevated PowerShell session and run the following cmdlets.
Установите модуль OneGet PowerShell. Install the OneGet PowerShell module.
С помощью OneGet установите последнюю версию Docker. Use OneGet to install the latest version of Docker.
После завершения установки перезагрузите компьютер. When the installation is complete, reboot the computer.
Установка конкретной версии Docker Install a specific version of Docker
На данный момент для Docker EE для Windows Server доступно два канала: There are currently two channels available for Docker EE for Windows Server:
- 17.06 — используйте эту версию, если вы используете Docker Enterprise Edition (Docker Engine, UCP, DTR). 17.06 — Use this version if you’re using Docker Enterprise Edition (Docker Engine, UCP, DTR). 17.06 используется по умолчанию. 17.06 is the default.
- 18.03 — используйте эту версию, если вы используете только подсистему Docker EE Engine. 18.03 — Use this version if you’re running Docker EE Engine alone.
Чтобы установить конкретную версию, используйте флаг RequiredVersion . To install a specific version, use the RequiredVersion flag:
Для установки конкретных версий Docker EE может потребоваться обновление ранее установленных модулей DockerMsftProvider. Installing specific Docker EE versions may require an update to previously installed DockerMsftProvider modules. Чтобы его выполнить, воспользуйтесь следующей командой: To Update:
Обновление Docker Update Docker
Если необходимо обновить более раннюю версию канала подсистемы Docker EE Engine до более поздней, используйте флаги -Update и -RequiredVersion . If you need to update Docker EE Engine from an earlier channel to a later channel, use both the -Update and -RequiredVersion flags:
Установка базовых образов контейнеров Install base container images
Перед началом работы с контейнерами Windows необходимо установить базовый образ. Before working with Windows containers, a base image needs to be installed. Базовые образы доступны при использовании Windows Server Core и Nano Server в качестве операционной системы контейнера. Base images are available with either Windows Server Core or Nano Server as the container operating system. Подробные сведения об образах контейнеров Docker см. в разделе Создание собственных образов на сайте docker.com. For detailed information on Docker container images, see Build your own images on docker.com.
Начиная с мая 2018 года, для обеспечения единообразных и надежных возможностей приобретения почти все образы контейнеров, полученные от Майкрософт, обслуживаются из Реестра контейнеров Майкрософт, mcr.microsoft.com. При этом текущий процесс обнаружения через Docker Hub остается неизменным. With effect from May 2018, delivering a consistent and trustworthy acquisition experience, almost all of the Microsoft-sourced container images are served from the Microsoft Container Registry, mcr.microsoft.com, while maintaining the current discovery process via Docker Hub.
Windows Server 2019 и более поздних версий Windows Server 2019 and newer
Чтобы установить базовый образ Windows Server Core, выполните следующую команду: To install the ‘Windows Server Core’ base image run the following:
Чтобы установить базовый образ Nano Server, выполните следующую команду: To install the ‘Nano Server’ base image run the following:
Windows Server 2016 (версии 1607–1803) Windows Server 2016 (versions 1607-1803)
Чтобы установить базовый образ Windows Server Core, выполните следующую команду: To install the Windows Server Core base image run the following:
Чтобы установить базовый образ Nano Server, выполните следующую команду: To install the Nano Server base image run the following:
Прочтите лицензионное соглашение для образов ОС контейнеров Windows на странице Лицензионное соглашение. Please read the Windows containers OS image EULA, which can be found here – EULA.
Узел с изоляцией Hyper-V Hyper-V isolation host
Для запуска изоляции Hyper-V необходима роль Hyper-V. You must have the Hyper-V role to run Hyper-V isolation. Если сам узел контейнера Windows является виртуальной машиной Hyper-V, перед установкой роли Hyper-V необходимо включить вложенную виртуализацию. If the Windows container host is itself a Hyper-V virtual machine, nested virtualization will need to be enabled before installing the Hyper-V role. Дополнительные сведения о вложенной виртуализации см. в статье Вложенная виртуализация. For more information on nested virtualization, see Nested Virtualization.
Вложенная виртуализация Nested virtualization
Приведенный ниже сценарий настраивает вложенную виртуализацию для узла контейнера. The following script will configure nested virtualization for the container host. Этот сценарий выполняется на родительском компьютере Hyper-V. This script is run on the parent Hyper-V machine. Перед запуском сценария убедитесь, что виртуальная машина узла контейнера отключена. Ensure that the container host virtual machine is turned off when running this script.
Включение роли Hyper-V Enable the Hyper-V role
Чтобы включить компонент Hyper-V с помощью PowerShell, выполните приведенный ниже командлет в сеансе PowerShell с повышенными правами. To enable the Hyper-V feature using PowerShell, run the following cmdlet in an elevated PowerShell session.
Dockerfile on Windows
The Docker engine includes tools that automate container image creation. While you can create container images manually by running the docker commit command, adopting an automated image creation process has many benefits, including:
- Storing container images as code.
- Rapid and precise recreation of container images for maintenance and upgrade purposes.
- Continuous integration between container images and the development cycle.
The Docker components that drive this automation are the Dockerfile, and the docker build command.
The Dockerfile is a text file that contains the instructions needed to create a new container image. These instructions include identification of an existing image to be used as a base, commands to be run during the image creation process, and a command that will run when new instances of the container image are deployed.
Docker build is the Docker engine command that consumes a Dockerfile and triggers the image creation process.
This topic will show you how to use Dockerfiles with Windows containers, understand their basic syntax, and what the most common Dockerfile instructions are.
This document will discuss the concept of container images and container image layers. If you want to learn more about images and image layering, see container base images.
For a complete look at Dockerfiles, see the Dockerfile reference.
Basic Syntax
In its most basic form, a Dockerfile can be very simple. The following example creates a new image, which includes IIS, and a вЂhello world’ site. This example includes comments (indicated with a # ), that explain each step. Subsequent sections of this article will go into more detail on Dockerfile syntax rules, and Dockerfile instructions.
A Dockerfile must be created with no extension. To do this in Windows, create the file with your editor of choice, then save it with the notation «Dockerfile» (including the quotes).
For additional examples of Dockerfiles for Windows, see the Dockerfile for Windows repository.
Instructions
Dockerfile instructions provide the Docker Engine the instructions it needs to create a container image. These instructions are performed one-by-one and in order. The following examples are the most commonly used instructions in Dockerfiles. For a complete list of Dockerfile instructions, see the Dockerfile reference.
The FROM instruction sets the container image that will be used during the new image creation process. For instance, when using the instruction FROM mcr.microsoft.com/windows/servercore , the resulting image is derived from, and has a dependency on, the Windows Server Core base OS image. If the specified image is not present on the system where the Docker build process is being run, the Docker engine will attempt to download the image from a public or private image registry.
The FROM instruction’s format goes like this:
Here’s an example of the FROM command:
To download the ltsc2019 version windows server core from the Microsoft Container Registry (MCR):
For more detailed information, see the FROM reference.
The RUN instruction specifies commands to be run, and captured into the new container image. These commands can include items such as installing software, creating files and directories, and creating environment configuration.
The RUN instruction goes like this:
The difference between the exec and shell form is in how the RUN instruction is executed. When using the exec form, the specified program is run explicitly.
Here’s an example of the exec form:
The resulting image runs the powershell New-Item c:/test command:
To contrast, the following example runs the same operation in shell form:
The resulting image has a run instruction of cmd /S /C powershell New-Item c:\test .
Considerations for using RUN with Windows
On Windows, when using the RUN instruction with the exec format, backslashes must be escaped.
When the target program is a Windows installer, you’ll need to extract the setup through the /x: flag before you can launch the actual (silent) installation procedure. You must also wait for the command to exit before you do anything else. Otherwise, the process will end prematurely without installing anything. For details, please consult the example below.
Examples of using RUN with Windows
The following example Dockerfile uses DISM to install IIS in the container image:
This example installs the Visual Studio redistributable package. Start-Process and the -Wait parameter are used to run the installer. This ensures that the installation completes before moving on to the next instruction in the Dockerfile.
For detailed information on the RUN instruction, see the RUN reference.
The COPY instruction copies files and directories to the container’s file system. The files and directories must be in a path relative to the Dockerfile.
The COPY instruction’s format goes like this:
If either source or destination includes white space, enclose the path in square brackets and double quotes, as shown in the following example:
Considerations for using COPY with Windows
On Windows, the destination format must use forward slashes. For example, these are valid COPY instructions:
Meanwhile, the following format with backslashes won’t work:
Examples of using COPY with Windows
The following example adds the contents of the source directory to a directory named sqllite in the container image:
The following example will add all files that begin with config to the c:\temp directory of the container image:
For more detailed information about the COPY instruction, see the COPY reference.
The ADD instruction is like the COPY instruction, but with even more capabilities. In addition to copying files from the host into the container image, the ADD instruction can also copy files from a remote location with a URL specification.
The ADD instruction’s format goes like this:
If either the source or destination include white space, enclose the path in square brackets and double quotes:
Considerations for running ADD with Windows
On Windows, the destination format must use forward slashes. For example, these are valid ADD instructions:
Meanwhile, the following format with backslashes won’t work:
Additionally, on Linux the ADD instruction will expand compressed packages on copy. This functionality is not available in Windows.
Examples of using ADD with Windows
The following example adds the contents of the source directory to a directory named sqllite in the container image:
The following example will add all files that begin with «config» to the c:\temp directory of the container image.
The following example will download Python for Windows into the c:\temp directory of the container image.
For more detailed information about the ADD instruction, see the ADD reference.
WORKDIR
The WORKDIR instruction sets a working directory for other Dockerfile instructions, such as RUN , CMD , and also the working directory for running instances of the container image.
The WORKDIR instruction’s format goes like this:
Considerations for using WORKDIR with Windows
On Windows, if the working directory includes a backslash, it must be escaped.
Examples
For detailed information on the WORKDIR instruction, see the WORKDIR reference.
The CMD instruction sets the default command to be run when deploying an instance of the container image. For instance, if the container will be hosting an NGINX web server, the CMD might include instructions to start the web server with a command like nginx.exe . If multiple CMD instructions are specified in a Dockerfile, only the last is evaluated.
The CMD instruction’s format goes like this:
Considerations for using CMD with Windows
On Windows, file paths specified in the CMD instruction must use forward slashes or have escaped backslashes \\ . The following are valid CMD instructions:
However, the following format without the proper slashes will not work:
For more detailed information about the CMD instruction, see the CMD reference.
Escape character
In many cases a Dockerfile instruction will need to span multiple lines. To do this, you can use an escape character. The default Dockerfile escape character is a backslash \ . However, because the backslash is also a file path separator in Windows, using it to span multiple lines can cause problems. To get around this, you can use a parser directive to change the default escape character. For more information about parser directives, see Parser directives.
The following example shows a single RUN instruction that spans multiple lines using the default escape character:
To modify the escape character, place an escape parser directive on the very first line of the Dockerfile. This can be seen in the following example.
Only two values can be used as escape characters: \ and ` .
For more information about the escape parser directive, see Escape parser directive.
PowerShell in Dockerfile
PowerShell cmdlets
PowerShell cmdlets can be run in a Dockerfile with the RUN operation.
REST calls
PowerShell’s Invoke-WebRequest cmdlet can be useful when gathering information or files from a web service. For instance, if you build an image that includes Python, you can set $ProgressPreference to SilentlyContinue to achieve faster downloads, as shown in the following example.
Invoke-WebRequest also works in Nano Server.
Another option for using PowerShell to download files during the image creation process is to use the .NET WebClient library. This can increase download performance. The following example downloads the Python software, using the WebClient library.
Nano Server does not currently support WebClient.
PowerShell scripts
In some cases, it may be helpful to copy a script into the containers you use during the image creation process, then run the script from within the container.
This will limit any image layer caching and decrease the Dockerfile’s readability.
This example copies a script from the build machine into the container using the ADD instruction. This script is then run using the RUN instruction.
Docker build
Once a Dockerfile has been created and saved to disk, you can run docker build to create the new image. The docker build command takes several optional parameters and a path to the Dockerfile. For complete documentation on Docker Build, including a list of all build options, see the build reference.
The format of the docker build command goes like this:
For example, the following command will create an image named «iis.»
When the build process has been initiated, the output will indicate status and return any thrown errors.
The result is a new container image, which in this example is named «iis.»