Dockerfile from windows 10

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.

Читайте также:  Почему принтер приостанавливает печать windows 10

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.»

Оптимизация файлов Dockerfile в Windows Optimize Windows Dockerfiles

Процесс сборки Docker и получаемые образы Docker можно оптимизировать несколькими способами. There are many ways to optimize both the Docker build process and the resulting Docker images. В этой статье объясняется, как происходит процесс сборки Docker и как оптимально создавать образы для контейнеров Windows. This article explains how the Docker build process works and how to optimally create images for Windows containers.

Слои образов в сборке Docker Image layers in Docker build

Чтобы оптимизировать сборку Docker, необходимо знать, как она выполняется. Before you can optimize your Docker build, you’ll need to know how Docker build works. В процессе сборки Docker используется файл Dockerfile, а также поочередно выполняются все активные инструкции, каждая в своем собственном временном контейнере. During the Docker build process, a Dockerfile is consumed, and each actionable instruction is run, one-by-one, in its own temporary container. В результате для каждой активной инструкции создается новый слой образа. The result is a new image layer for each actionable instruction.

Например, в следующем примере Dockerfile использует базовый образ ОС mcr.microsoft.com/windows/servercore:ltsc2019 , устанавливает службы IIS, а затем создает простой веб-сайт. For example, the following sample Dockerfile uses the mcr.microsoft.com/windows/servercore:ltsc2019 base OS image, installs IIS, and then creates a simple website.

Вам может показаться, что файл Dockerfile создаст образ с двумя слоями: один для образа ОС контейнера, а второй — для служб IIS и веб-сайта. You might expect that this Dockerfile will produce an image with two layers, one for the container OS image, and a second that includes IIS and the website. Однако фактический образ состоит из нескольких слоев, и каждый из них зависит от предыдущего. However, the actual image has many layers, and each layer depends upon the one before it.

Читайте также:  Создать сеть по wifi между компами windows 10

Чтобы лучше это понять, давайте применим команду docker history к образу, созданному с помощью нашего примера файла Dockerfile. To make this clearer, let’s run the docker history command against the image our sample Dockerfile made.

Выходные данные свидетельствуют о том, что в этом образе есть четыре слоя: базовый и три дополнительных, сопоставленных с каждой инструкцией в Dockerfile. The output shows us that this image has four layers: the base layer and three additional layers that are mapped to each instruction in the Dockerfile. Нижний слой (в этом примере — 6801d964fda5 ) представляет базовый образ ОС. The bottom layer ( 6801d964fda5 in this example) represents the base OS image. Одним слоем выше находится установка служб IIS. One layer up is the IIS installation. Следующий слой включает новый веб-сайт и т. д. The next layer includes the new website, and so on.

Файлы Dockerfile можно составлять таким образом, чтобы свести к минимуму число слоев в образе, оптимизировать производительность сборки, а также повысить доступность за счет удобочитаемости. Dockerfiles can be written to minimize image layers, optimize build performance, and optimize accessibility through readability. По сути, существует множество способов выполнить одну и ту же задачу сборки образа. Ultimately, there are many ways to complete the same image build task. Понимание того, как формат файла Dockerfile влияет на время сборки и создаваемый образ, расширяет возможности автоматизации. Understanding how the Dockerfile’s format affects build time and the image it creates improves the automation experience.

Оптимизация размера образа Optimize image size

В зависимости от требований к пространству при создании образов контейнеров Docker важную роль может играть размер образа. Depending on your space requirements, image size can be an important factor when building Docker container images. Образы контейнеров перемещаются между реестрами и узлом, экспортируются и импортируются и в конечном счете занимают определенное место. Container images are moved between registries and host, exported and imported, and ultimately consume space. В этом разделе вы узнаете, как свести к минимуму размер образа в процессе сборки Docker для контейнеров Windows. This section will tell you how to minimize image size during the Docker build process for Windows containers.

Дополнительные сведения о рекомендациях для файлов Dockerfile см. в советах по составлению файлов Dockerfile на сайте Docker.com. For additional information about Dockerfile best practices, see Best practices for writing Dockerfiles on Docker.com.

Поскольку каждая инструкция RUN создает новый слой в образе контейнера, группирование действий в одной инструкции RUN позволяет сократить число слоев в файле Dockerfile. Because each RUN instruction creates a new layer in the container image, grouping actions into one RUN instruction can reduce the number of layers in a Dockerfile. Хотя минимизация числа слоев может не влиять на размер образа, группирование связанных действий влияет на него, что видно в приведенных ниже примерах. While minimizing layers may not affect image size much, grouping related actions can, which will be seen in subsequent examples.

В этом разделе мы будем сравнивать два примера файлов Dockerfile, которые выполняют одни и те же действия. In this section, we’ll compare two example Dockerfiles that do the same things. Однако в одном файле Dockerfile используется одна инструкция для каждого действия, а в другом — связанные действия сгруппированы вместе. However, one Dockerfile has one instruction per action, while the other had its related actions grouped together.

В следующем примере несгруппированный файл Dockerfile скачивает Python для Windows, устанавливает его и удаляет скачанный файл установки после завершения установки. The following ungrouped example Dockerfile downloads Python for Windows, installs it, and removes the downloaded setup file once installation is done. В этом файле Dockerfile для каждого действия предусмотрена отдельная инструкция RUN . In this Dockerfile, each action is given its own RUN instruction.

Полученный образ имеет три дополнительных слоя — по одному для каждой инструкции RUN . The resulting image consists of three additional layers, one for each RUN instruction.

Второй пример — это фал Dockerfile, выполняющий точно такую же операцию. The second example is a Dockerfile that performs the exact same operation. Однако все связанные действия сгруппированы в одной инструкции RUN . However, all related actions have been grouped under a single RUN instruction. Каждый шаг в инструкции RUN начинается с новой строки в файле Dockerfile, при этом для переноса строки используется символ «\». Each step in the RUN instruction is on a new line of the Dockerfile, while the ‘\’ character is used to line wrap.

Полученный образ имеет один дополнительный слой для инструкции RUN . The resulting image has only one additional layer for the RUN instruction.

Удаление лишних файлов Remove excess files

Если в Dockerfile есть какой-либо файл, например установщик, который не требуется после его использования, его можно удалить, чтобы уменьшить размер образа. If there’s a file in your Dockerfile, such as an installer, that you don’t need after it’s been used, you can remove it to reduce image size. Это следует делать на том же шаге, где данный файл был скопирован в слой образа. This needs to occur in the same step in which the file was copied into the image layer. Эта процедура предотвращает сохранение файла в слое образа более низкого уровня. Doing so prevents the file from persisting in a lower-level image layer.

В следующем примере файла Dockerfile пакет Python загружается, выполняется, а затем удаляется. In the following example Dockerfile, the Python package is downloaded, executed, then removed. Все это выполняется в рамках одной операции RUN и создает всего один слой образа. This is all completed in one RUN operation and results in a single image layer.

Оптимизация скорости сборки Optimize build speed

Несколько строк Multiple lines

Чтобы оптимизировать скорость сборки Docker, можно разделить операции на несколько отдельных инструкций. You can split operations into multiple individual instructions to optimize Docker build speed. Несколько операций RUN повышают эффективность кэширования, так как для каждой инструкции RUN создаются отдельные слои. Multiple RUN operations increase caching effectiveness because individual layers are created for each RUN instruction. Если какая-либо инструкция уже выполнялась в другой операции сборки Docker, такая кэшированная операция (слой образа) используется повторно, что приводит к сокращению времени выполнения сборки Docker. If an identical instruction was already run in a different Docker Build operation, this cached operation (image layer) is reused, resulting in decreased Docker build runtime.

Читайте также:  Postgres linux user password

В следующем примере загружаются и устанавливаются распространяемые пакеты Apache и Visual Studio, после чего ненужные больше файлы удаляются. In the following example, both Apache and the Visual Studio Redistribute packages are downloaded, installed, and then cleaned up by removing files that are no longer needed. Все это выполняется в рамках одной инструкции RUN . This is all done with a single RUN instruction. При изменении любого из этих действий все они перезапускаются. If any of these actions are updated, all actions will rerun.

Итоговый образ имеет два слоя — один для базового образа ОС, а второй для всех операций из одной инструкции RUN . The resulting image has two layers, one for the base OS image, and one that contains all operations from the single RUN instruction.

По сравнению с предыдущим примером здесь те же действия поделены между тремя инструкциями RUN . By comparison, here are the same actions split into three RUN instructions. В этом случае каждая инструкция RUN кэшируется в слое образа контейнера, а при последующих сборках Dockerfile повторно выполняются только измененные инструкции. In this case, each RUN instruction is cached in a container image layer, and only those that have changed need to be rerun on subsequent Dockerfile builds.

Полученный образ имеет четыре слоя — один для базового образа ОС и по одному для каждой из трех инструкций RUN . The resulting image consists of four layers; one layer for the base OS image and each of the three RUN instructions. Так как каждая инструкция RUN выполняется в отдельном слое, при всех последующих запусках этого файла Dockerfile или аналогичного набора инструкций из другого Dockerfile будет использоваться кэшированный слой образа, что сокращает время сборки. Because each RUN instruction ran in its own layer, any subsequent runs of this Dockerfile or identical set of instructions in a different Dockerfile will use cached image layers, reducing build time.

Как показано в следующем разделе, при работе с кэшами образов порядок выполнения инструкций играет важную роль. How you order the instructions is important when working with image caches, as you’ll see in the next section.

Порядок инструкций Ordering instructions

Файл Dockerfile обрабатывается сверху вниз, при этом каждая инструкция сравнивается с кэшированными слоями. A Dockerfile is processed from top to the bottom, each Instruction compared against cached layers. При обнаружении инструкции без кэшированного слоя она и все последующие инструкции обрабатываются в новых слоях образа контейнера. When an instruction is found without a cached layer, this instruction and all subsequent instructions are processed in new container image layers. Поэтому порядок инструкций имеет важное значение. Because of this, the order in which instructions are placed is important. Инструкции, которые останутся постоянными, располагайте ближе к началу файла Dockerfile. Place instructions that will remain constant towards the top of the Dockerfile. Инструкции, которые могут изменяться, располагайте ближе к концу файла Dockerfile. Place instructions that may change towards the bottom of the Dockerfile. Это снижает вероятность отмены существующего кэша. Doing so reduces the likelihood of negating existing cache.

Следующие примеры демонстрируют, как порядок инструкций в файле Dockerfile влияет на эффективность кэширования. The following examples show how Dockerfile instruction ordering can affect caching effectiveness. В этом простом файле Dockerfile имеется четыре нумерованных папки. This simple example Dockerfile has four numbered folders.

Полученный образ имеет пять слоев — один для базового образа ОС и по одному для каждой инструкции RUN . The resulting image has five layers, one for the base OS image and each of the RUN instructions.

Следующий файл Dockerfile теперь немного изменился (в качестве третьей инструкции RUN используется новый файл). This next Dockerfile has now been slightly modified, with the third RUN instruction changed to a new file. При запуске сборки Docker для этого файла Dockerfile три первых инструкции, которые идентичны инструкциям з прошлого примера, используют кэшированные слои образа. When Docker build is run against this Dockerfile, the first three instructions, which are identical to those in the last example, use the cached image layers. Однако поскольку измененная инструкция RUN не кэшируется, для нее и всех последующих инструкций создается новый слой. However, because the changed RUN instruction isn’t cached, a new layer is created for the changed instruction and all subsequent instructions.

При сравнении идентификаторов нового образа с образом в первом примере этого раздела можно заметить, что первые три слоя снизу вверх являются общими, а четвертый и пятый — уникальными. When you compare the image IDs of the new image to that in this section’s first example, you’ll notice that the first three layers from bottom to top are shared, but the fourth and fifth are unique.

Косметическая оптимизация Cosmetic optimization

Регистр инструкций Instruction case

В инструкциях Dockerfile не учитывается регистр, однако принято использовать верхний регистр. Dockerfile instructions are not case-sensitive, but the convention is to use upper case. Это улучшает удобочитаемость, разделяя вызов инструкции и операцию инструкции. This improves readability by differentiating between the Instruction call and instruction operation. В следующих двух примерах сравниваются файлы Dockerfile с инструкциями, написанными в верхнем и нижнем регистре. The following two examples compare an uncapitalized and capitalized Dockerfile.

Ниже приведен файл Dockerfile с инструкциями в нижнем регистре: The following is an uncapitalized Dockerfile:

Далее приведен тот же Dockerfile, но с инструкциями в верхнем регистре: The following is the same Dockerfile using upper-case:

Перенос строк Line wrapping

Длинные и сложные операции можно разделить на несколько строк с помощью символа обратной косой черты \ . Long and complex operations can be separated onto multiple lines by the backslash \ character. Следующий файл Dockerfile устанавливает распространяемый пакет Visual Studio, удаляет файлы установщика и затем создает файл конфигурации. The following Dockerfile installs the Visual Studio Redistributable package, removes the installer files, and then creates a configuration file. Все эти три операции указаны на одной строке. These three operations are all specified on one line.

Команду можно разбить на части с помощью обратной косой черты, чтобы каждая операция из инструкции RUN была указана в отдельной строке. The command can be broken up with backslashes so that each operation from the one RUN instruction is specified on its own line.

Оцените статью