- Dockerfile в Windows Dockerfile on Windows
- Базовый синтаксис Basic Syntax
- Инструкция Instructions
- FROM FROM
- RUN RUN
- Рекомендации по использованию инструкции RUN с Windows Considerations for using RUN with Windows
- Примеры использования инструкции RUN с Windows Examples of using RUN with Windows
- COPY COPY
- Рекомендации по использованию инструкции COPY с Windows Considerations for using COPY with Windows
- Примеры использования инструкции COPY с Windows Examples of using COPY with Windows
- ДОБАВИТЬ ADD
- Рекомендации по выполнению инструкции ADD с Windows Considerations for running ADD with Windows
- Примеры использования инструкции ADD с Windows Examples of using ADD with Windows
- WORKDIR WORKDIR
- Рекомендации по использованию инструкции WORKDIR с Windows Considerations for using WORKDIR with Windows
- CMD CMD
- Рекомендации по использованию инструкции CMD с Windows Considerations for using CMD with Windows
- Escape-символ Escape character
- PowerShell в Dockerfile PowerShell in Dockerfile
- Командлеты PowerShell PowerShell cmdlets
- Вызовы REST REST calls
- Сценарии PowerShell PowerShell scripts
- Команда Docker build Docker build
Dockerfile в Windows Dockerfile on Windows
Подсистема Docker содержит средства, автоматизирующие создание образов контейнеров. The Docker engine includes tools that automate container image creation. Хотя образы контейнеров можно создавать вручную с помощью команды docker commit , внедрение процесса автоматического создания образа предоставляет множество преимуществ, в том числе: 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.
За такую автоматизацию отвечают два компонента Docker — файл Dockerfile и команда docker build . The Docker components that drive this automation are the Dockerfile, and the docker build command.
Dockerfile — это текстовый файл с инструкциями, необходимыми для создания образа контейнера. 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 — команда подсистемы Docker, использующая файл Dockerfile и запускающая процесс создания образа. Docker build is the Docker engine command that consumes a Dockerfile and triggers the image creation process.
В этом разделе рассказывается о том, как использовать файлы Dockerfile с контейнерами Windows, а также объясняются наиболее распространенные инструкции и базовый синтаксис таких файлов. 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.
Полный обзор файлов Dockerfile см. в справке по Dockerfile на странице . For a complete look at Dockerfiles, see the Dockerfile reference.
Базовый синтаксис Basic Syntax
В исходной форме файл Dockerfile может быть очень простым. In its most basic form, a Dockerfile can be very simple. Следующий пример создает образ, включающий IIS и сайт «hello world». 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. В последующих разделах этой статьи более подробно рассматриваются правила синтаксиса Dockerfile и инструкции Dockerfile. Subsequent sections of this article will go into more detail on Dockerfile syntax rules, and Dockerfile instructions.
Файл Dockerfile необходимо создавать без расширения. A Dockerfile must be created with no extension. Чтобы сделать это в Windows, создайте файл с помощью удобного для вас редактора, а затем сохраните его, используя нотацию «Dockerfile» (вместе с кавычками). To do this in Windows, create the file with your editor of choice, then save it with the notation «Dockerfile» (including the quotes).
Дополнительные примеры файлов Dockerfile для Windows см. в репозитории файлов Dockerfile для Windows. For additional examples of Dockerfiles for Windows, see the Dockerfile for Windows repository.
Инструкция Instructions
Инструкции Dockerfile дают подсистеме Docker необходимые указания для создания образа контейнера. 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. Ниже приведены примеры наиболее часто используемых инструкций в файлах Dockerfile. The following examples are the most commonly used instructions in Dockerfiles. Полный список инструкций Dockerfile см. в справочнике по файлам Dockerfile. For a complete list of Dockerfile instructions, see the Dockerfile reference.
FROM FROM
Инструкция FROM задает образ контейнера, который будет применяться при создании нового образа. The FROM instruction sets the container image that will be used during the new image creation process. Например, при использовании инструкции FROM mcr.microsoft.com/windows/servercore полученный образ является производным и зависимым от базового образа ОС Windows Server Core. 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. Если указанный образ отсутствует в системе, где выполняется процесс сборки Docker, подсистема Docker попытается скачать его из общедоступного или частного реестра образов. 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.
Формат инструкции FROM выглядит следующим образом: The FROM instruction’s format goes like this:
Ниже приведен пример команды FROM. Here’s an example of the FROM command:
Чтобы загрузить Windows Server Core версии ltsc2019 из Реестра контейнеров (Майкрософт): To download the ltsc2019 version windows server core from the Microsoft Container Registry (MCR):
Дополнительные сведения см. в справочнике по инструкции FROM. For more detailed information, see the FROM reference.
RUN RUN
Инструкция RUN задает команды, которые следует выполнить и поместить в новый образ контейнера. 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.
Инструкция RUN выглядит следующим образом: The RUN instruction goes like this:
Различие между формой исполняемого файла (exec form) и формой оболочки (shell form) заключается в способе выполнения инструкции RUN . 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:
Полученный образ выполняет команду powershell New-Item c:/test : The resulting image runs the powershell New-Item c:/test command:
В отличие от предыдущего примера здесь та же операция выполняется с использованием формы оболочки: To contrast, the following example runs the same operation in shell form:
Полученный образ содержит инструкцию RUN cmd /S /C powershell New-Item c:\test . The resulting image has a run instruction of cmd /S /C powershell New-Item c:\test .
Рекомендации по использованию инструкции RUN с Windows Considerations for using RUN with Windows
В Windows при использовании инструкции RUN в формате исполняемого файла необходимо экранировать инструкции символы обратной косой черты. On Windows, when using the RUN instruction with the exec format, backslashes must be escaped.
Если целевая программа является установщиком Windows, чтобы запустить фактическую процедуру (автоматической) установки, необходимо извлечь программу установки, используя флаг /x: . 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.
Примеры использования инструкции RUN с Windows Examples of using RUN with Windows
В следующем примере для установки служб IIS в образе контейнера используется система DISM. The following example Dockerfile uses DISM to install IIS in the container image:
Этот пример устанавливает распространяемый пакет Visual Studio. This example installs the Visual Studio redistributable package. Start-Process и параметр -Wait используются для запуска программы установки. Start-Process and the -Wait parameter are used to run the installer. Это гарантирует, что установка будет завершена до перехода к следующей инструкции в Dockerfile. This ensures that the installation completes before moving on to the next instruction in the Dockerfile.
Подробные сведения об инструкции RUN см. в справочнике по RUN на странице . For detailed information on the RUN instruction, see the RUN reference.
COPY COPY
Инструкция COPY копирует файлы и каталоги в файловую систему контейнера. The COPY instruction copies files and directories to the container’s file system. Эти файлы и каталоги должны иметь путь, являющийся относительным для Dockerfile. The files and directories must be in a path relative to the Dockerfile.
Формат инструкции COPY выглядит следующим образом: 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:
Рекомендации по использованию инструкции COPY с Windows Considerations for using COPY with Windows
В Windows для путей назначения необходимо использовать символы косой черты. On Windows, the destination format must use forward slashes. Например, здесь показаны допустимые инструкции COPY . For example, these are valid COPY instructions:
При этом следующий формат с обратными косыми чертами работать не будет: Meanwhile, the following format with backslashes won’t work:
Примеры использования инструкции COPY с Windows Examples of using COPY with Windows
В следующем примере содержимое исходного каталога добавляется в каталог с именем sqllite в образе контейнера. The following example adds the contents of the source directory to a directory named sqllite in the container image:
В следующем примере все файлы, начинающиеся с config, добавляют в каталог c:\temp образа контейнера. The following example will add all files that begin with config to the c:\temp directory of the container image:
Дополнительные сведения об инструкции COPY см. в справочнике по инструкции COPY. For more detailed information about the COPY instruction, see the COPY reference.
ДОБАВИТЬ ADD
Инструкция ADD похожа на инструкцию COPY, но с дополнительными возможностями. The ADD instruction is like the COPY instruction, but with even more capabilities. Кроме копирования файлов с узла в образ контейнера, инструкция ADD также позволяет скопировать файлы из удаленного расположения с помощью задания URL-адреса. 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.
Формат инструкции ADD выглядит следующим образом: 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:
Рекомендации по выполнению инструкции ADD с Windows Considerations for running ADD with Windows
В Windows для путей назначения необходимо использовать символы косой черты. On Windows, the destination format must use forward slashes. Например, здесь показаны допустимые инструкции ADD . For example, these are valid ADD instructions:
При этом следующий формат с обратными косыми чертами работать не будет: Meanwhile, the following format with backslashes won’t work:
Кроме того, в системе Linux во время копирования инструкция ADD распаковывает сжатые пакеты. Additionally, on Linux the ADD instruction will expand compressed packages on copy. В Windows эта функция недоступна. This functionality is not available in Windows.
Примеры использования инструкции ADD с Windows Examples of using ADD with Windows
В следующем примере содержимое исходного каталога добавляется в каталог с именем sqllite в образе контейнера. The following example adds the contents of the source directory to a directory named sqllite in the container image:
В следующем примере все файлы, начинающиеся с «config», добавляют в каталог c:\temp образа контейнера. The following example will add all files that begin with «config» to the c:\temp directory of the container image.
В этом примере Python для Windows скачивается в каталог c:\temp образа контейнера. The following example will download Python for Windows into the c:\temp directory of the container image.
Дополнительные сведения об инструкции ADD см. в справочнике по инструкции ADD. For more detailed information about the ADD instruction, see the ADD reference.
WORKDIR WORKDIR
Инструкция WORKDIR задает рабочий каталог для других инструкций Dockerfile, например RUN и CMD , а также рабочий каталог для запущенных экземпляров образа контейнера. 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.
Формат инструкции WORKDIR выглядит следующим образом: The WORKDIR instruction’s format goes like this:
Рекомендации по использованию инструкции WORKDIR с Windows Considerations for using WORKDIR with Windows
Если в Windows рабочий каталог содержит обратную косую черту, ее следует экранировать. On Windows, if the working directory includes a backslash, it must be escaped.
Примеры Examples
Подробные сведения об инструкции WORKDIR см. в справочнике по WORKDIR. For detailed information on the WORKDIR instruction, see the WORKDIR reference.
CMD CMD
Инструкция CMD задает команду по умолчанию, выполняемую при развертывании экземпляра образа контейнера. The CMD instruction sets the default command to be run when deploying an instance of the container image. Например, если в контейнере будет размещен веб-сервер NGINX, CMD может включать инструкции для запуска этого веб-сервера, например с помощью команды nginx.exe . 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 . Если в файле Dockerfile указано несколько инструкций CMD , вычисляется только последняя из них. If multiple CMD instructions are specified in a Dockerfile, only the last is evaluated.
Формат инструкции CMD выглядит следующим образом: The CMD instruction’s format goes like this:
Рекомендации по использованию инструкции CMD с Windows Considerations for using CMD with Windows
В Windows для путей к файлам, указанным в инструкции CMD , следует использовать символы косой черты или экранировать символы обратной косой черты \\ . On Windows, file paths specified in the CMD instruction must use forward slashes or have escaped backslashes \\ . Допустимы следующие инструкции CMD : The following are valid CMD instructions:
Однако следующий формат без соответствующих косых черт работать не будет: However, the following format without the proper slashes will not work:
Дополнительные сведения об инструкции CMD см. в справочнике по инструкции CMD. For more detailed information about the CMD instruction, see the CMD reference.
Escape-символ Escape character
Во многих случаях инструкция Dockerfile должна занимать несколько строк. In many cases a Dockerfile instruction will need to span multiple lines. Для этого можно использовать escape-символ. To do this, you can use an escape character. Escape-символ Dockerfile по умолчанию — обратная косая черта ( \ ). The default Dockerfile escape character is a backslash \ . Однако, поскольку обратная косая черта также является разделителем пути к файлу в Windows, использование его для разделения нескольких строк может вызвать проблемы. However, because the backslash is also a file path separator in Windows, using it to span multiple lines can cause problems. Чтобы их избежать, можно изменить escape-символ по умолчанию с помощью директивы анализатора. 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.
В следующем примере показана инструкция RUN, которая занимает несколько строк и использует escape-символ по умолчанию. The following example shows a single RUN instruction that spans multiple lines using the default escape character:
Чтобы изменить escape-символ, поместите директиву Parser для escape-символа на первую строку Dockerfile. 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.
В качестве escape-символов можно использовать только символы: \ и ` . Only two values can be used as escape characters: \ and ` .
Дополнительные сведения о директиве анализатора для escape-символа см. в этом разделе. For more information about the escape parser directive, see Escape parser directive.
PowerShell в Dockerfile PowerShell in Dockerfile
Командлеты PowerShell PowerShell cmdlets
Командлеты PowerShell можно выполнять в Dockerfile при помощи операции RUN . PowerShell cmdlets can be run in a Dockerfile with the RUN operation.
Вызовы REST REST calls
При сборе данных или файлов из веб-службы удобно использовать командлет PowerShell Invoke-WebRequest . PowerShell’s Invoke-WebRequest cmdlet can be useful when gathering information or files from a web service. Например, при сборке образа, включающего Python, можно задать для $ProgressPreference значение SilentlyContinue , чтобы ускорить загрузку, как показано в следующем примере. 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 также работает на сервере Nano Server. Invoke-WebRequest also works in Nano Server.
Кроме того, с помощью PowerShell можно скачивать файлы во время создания образа, используя библиотеку .NET WebClient. 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. Следующий пример скачивает программное обеспечение Python, используя библиотеку WebClient. The following example downloads the Python software, using the WebClient library.
Сейчас Nano Server не поддерживает WebClient. Nano Server does not currently support WebClient.
Сценарии PowerShell 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.
Это ограничивает возможности кэширования слоев образов, а также ухудшает удобочитаемость файла Dockerfile. This will limit any image layer caching and decrease the Dockerfile’s readability.
Этот пример копирует сценарий с компьютера сборки в контейнер с помощью инструкции ADD . This example copies a script from the build machine into the container using the ADD instruction. Затем этот сценарий выполняется с помощью инструкции RUN. This script is then run using the RUN instruction.
Команда Docker build Docker build
После создания файла Dockerfile и сохранения его на диск можно запустить docker build для создания нового образа. Once a Dockerfile has been created and saved to disk, you can run docker build to create the new image. Команда docker build принимает несколько необязательных параметров и путь к файлу Dockerfile. The docker build command takes several optional parameters and a path to the Dockerfile. Полную документацию по команде Docker build, включая список всех параметров сборки, см. в справочнике по сборке. For complete documentation on Docker Build, including a list of all build options, see the build reference.
Формат команды docker build выглядит следующим образом: The format of the docker build command goes like this:
Например, следующая команда создает образ с именем «iis». 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.
В результате создается новый образ контейнера, который в этом примере носит имя «iis». The result is a new container image, which in this example is named «iis.»