How to run dockerfile
How to run dockerfile
Search Results
No Results
Filters
How to Use a Dockerfile to Build a Docker Image
A Dockerfile is a text file of instructions which are used to automate installation and configuration of a Docker image. Dockerfiles make it easy to deploy multiple Docker containers without having to maintain the same image across multiple virtual machines. Instructions are executed in the order they appear in the Dockerfile, which makes using and updating them clear and intuitive. This article covers the basics, with an example, of how a Dockerfile works.
Before You Begin
Familiarize yourself with our Getting Started guide, create and update a Linode, and install Docker. Alternatively, you can quickly deploy an updated, Docker-enabled Linode with the Docker Marketplace App.
Ensure your Linode is secure by following our guide on Setting Up and Securing a Compute Instance.
This guide assumes you are comfortable with using the Docker command-line interface (CLI). To learn more about the Docker CLI, check out their documentation.
How Does a Dockerfile Work?
A Dockerfile is a script that carries out different commands and actions to build a Docker image, which can then be used to deploy a Docker container. The commands and information within the Dockerfile can be configured to use specific software versions and dependencies for stable deployments. You can also use a Docker registry to store and access your public (or private) Docker images.
Here are common instructions that you can use in your Dockerfiles to build images:
Basic Definitions
Variables
Command Execution
Data Management
Networking
Next, we will create an example Dockerfile that utilizes some of these commands.
Creating a Dockerfile
To create the Dockerfile:
At the command prompt (either via SSH or Lish in the Linode Manager), create and change to a new directory:
Create an example Dockerfile:
Open the Dockerfile using the text editor of your choice (for this example, we use nano):
Copy the following example into your Dockerfile. This creates a Dockerfile that generates a Debian image, sets the maintainer information, and simply returns “Hello, Sunshine!” when run:
Save the Dockerfile.
Enter cat example_dockerfile and ensure the text from above is included.
Building a Docker Image from a Dockerfile
Build the image from the Dockerfile using the docker build command:
Labelling your image with example_image makes it easier to deploy a container in the next step.
The output should look something like this:
As you can see, the instructions from example_dockerfile are executed in order. The image labelled example_image is now ready for running to deploy a container.
Running Your Docker Image to Deploy a Container
Running the image you just built to deploy a Docker container is now as easy as entering the following:
A new container based on example_image is deployed, and the command specified in the CMD instruction is then executed from the container with the following output:
Further Reading
Congratulations! You’ve built your first Dockerfile and run your first Docker image.
For more examples and information on using Dockerfiles with Docker images and containers, see:
More Information
You may wish to consult the following resources for additional information on this topic. While these are provided in the hope that they will be useful, please note that we cannot vouch for the accuracy or timeliness of externally hosted materials.
This page was originally published on Friday, August 11, 2017.
How To Use A Dockerfile
In the earlier Docker articles, we were able to build images and get them running as containers manually. In this tutorial, we will explore how to take this a step further by building images with code. This is where the Dockerfile comes into play. Dockerfiles are small programs that describe how to assemble a Docker image. You can run these small programs using the docker build command. Once the docker build command finishes running the Dockerfile, a new Docker image will be placed into the local Docker Registry on your computer. Once you have a suitable image, you can run it with the docker container run command.
What Is A Dockerfile?
Each Step Produces An Image
Each step of the build process produces a new image. The build sequence is a series of steps where it starts with one image, makes a container out of it, run something in it, make a new image. The image in the prior step is unchanged. Each next step is saying, start from the prior step, make some new changes, then save to a new image. Dockerfiles are not shell scripts though they do look like shell scripts, because that helps them be familiar to people, and it makes them a little easier to learn. Processes you start on one line will not be running on the next line. You run them, they run for the duration of that container, then that container gets shut down, saved into an image, and begin anew on the next line. We’ll run through several examples to see how this works.
A Basic Dockerfile In Action
To get started with a Dockerfile, we can begin with only three commands to keep things simple. You will find these commands in virtually all Dockerfiles you encounter.
First, create a file named Dockerfile with no extension at all in the directory of your choosing.
Now, we can populate that file with the following commands.
Running A Dockerfile
Now comes the fun part. We want to run the Dockerfile we just created. Recall that this can be done with the docker build command which is a part of the builder management collection of the commands. The -t we include is simply tagging the image with a name so we have something to reference it by, otherwise, the resulting image would have only a cryptic id and no easily readable name. The other point to note is that there is a dot at the end of the command. That just says, use the Dockerfile in this directory we are in.
The image is built successfully and shows up in both Visual Studio Code and the Docker Dashboard.
Let’s go through what happened here. The first thing we see is “Sending build context to Docker daemon”. This is the Docker client sending the build context to the Docker daemon. That build context is the entire directory the Dockerfile is in. Following this, Docker will print out each step of the build process. In step one of three we have the following:
This step simply downloads and creates an image from busybox, which is very small and has nothing but a shell in it. Then the build process moves to step 2 of 3.
During step two it starts from that image, creates a container, and runs the command provided. From that running container, the echo of “building simple docker image” is run. During this step the 8b4d5802aed5 image is created. There is an intermediate of 1ec98c10d7d4 which was used to run our build step. Docker is smart enough to know that this intermediate container is not going to be used anywhere else in the Dockerfile, so it cleans up the intermediate container. This brings us to step 3 of 3.
During the final step, Docker sets the CMD to be run when this container starts. It is updating the state of the image. This step resulted in another intermediate container 7c4e7b0aa45b which is used temporarily in order to commit to the final image. Like the prior step, once it is no longer needed, it is removed. So the final result is the 2cd663381747 image. This is it’s image id. Since we tagged (read – named) the image as part of the build process, we can see that my-container is referring to the 2cd663381747 image.
Running Your Image
The section above showed how to build the most basic of images in Docker by using a Dockerfile. The build went successfully, and we now see the image in our local registry. Well, images were made for running, so let’s go ahead and spin up a container from our newly built image!
WORKDIR and COPY Example
Now let’s build another image, but make it a little more interesting. We’re going to build and run an Nginx Container while also adding our own custom HTML and CSS into the container during build time. That way we can see our own HTML page rather than the default Nginx splash page. In the practice directory add these two files.
css.css
index.html
Dockerfile
Viewing image layers on Docker Hub.
Viewing nginx image history.
Before we build an image using this Dockerfile, let’s confirm we have no images on the system currently.
The build went well, and we see the new image in Docker Desktop.
At this point, we have built an image but do not have a running container. Let’s confirm.
Let’s run our new container!
Ok, the container is running well!
Now visit http://localhost and you can see the new custom nginx container!
Commonly Used Dockerfile Commands
In this section, let’s look at the most commonly used Dockerfile commands. The ones to pay the most attention to are FROM, ENV, RUN, EXPOSE, and CMD.
The FROM Statement
The FROM statement just says what image to start running from. This should always be the first expression in a Dockerfile. It’s actually okay to put multiples of them in a Dockerfile. It means that the Dockerfile produces more than one image.
The RUN Statement
The RUN statement says to run a command through the shell. For example RUN unzip the install.zip file into this directory or RUN hello docker.
The CMD Statement
This is required and is the final command that will be run every time you launch a new container from the image. It also holds true anytime you restart a stopped container.
The LABEL Statement
The ENV Statement
The Environment statement sets environment variables like ENV DB_HOST=db.production.example.com or DB_PORT is 5432.
The EXPOSE Statement
The COPY Statement
The ADD Statement
The ADD statement is a very useful expression that you can use to add a local file and perform other tasks. It can also add the content from an archive. So, if you say ADD project.tar.gz to /install, it doesn’t copy the file tar.gz into that directory, it notices that it’s a compressed archive and it uncompresses all the files in that archive to that directory. It also works with URLs. You can say ADD the thing that you download from this big URL to /project. That would cause project.rpm to get download and put in project/project.rmp.
The WORKDIR Statement
The VOLUME Statement
Creates a mount point with the specified name and marks it as holding externally mounted volumes from native host or other containers.
The ENTRYPOINT Statement
ENTRYPOINT is similar to CMD, but it specifies the beginning of the expression to use when starting your container and lets you tack more on the end. So, if your container has an entry point of LS, then anything you type when you say Docker run my image name would be treated as arguments to the LS command. CMD specifies the whole command to run, and if the person, when they’re running the container, types something after Docker run image name, that will be run instead of CMD. ENTRYPOINT gets added to when people add arguments to your container and CMD gets replaced when people add arguments to your container. You can actually use both of them together. If you have them both, they get strung together, one after the other. In general, if you’re trying to make something that looks like a program and you want people to not care that it’s running inside a Docker container, ENTRYPOINT is for making your containers look like normal programs. CMD is the more commonly used approach.
The USER Statement
The USER statement says, I would like the commands run in this container to run as the user John, or maybe that user’s identified by number, USER 5000. This can be useful if you have shared network directories involved that assume a fixed username or a fixed user number.
The USER instruction sets the user name or UID to use when running the image and for any RUN, CMD and ENTRYPOINT instructions that follow it in the Dockerfile.
The ONBUILD Statement
The ARG Statement
The SHELL Statement
The HEALTHCHECK Statement
The STOPSIGNAL Statement
The STOPSIGNAL instruction sets the system call signal that will be sent to the container to exit. This signal can be a valid unsigned number that matches a position in the kernel’s syscall table, for instance 9, or a signal name in the format SIGNAME, for instance SIGKILL.
All About Dockerfiles
We covered a lot of great topics in this Dockerfile tutorial. To get even more familiar with Dockerfiles and how to use them, check out the additional resources below.
Dockerfile в Windows
Dockerfile — это текстовый файл с инструкциями, необходимыми для создания образа контейнера. Эти инструкции включают идентификацию существующего образа, используемого в качестве основы, команды, выполняемые в процессе создания образа, и команду, которая будет выполняться при развертывании новых экземпляров этого образа контейнера.
Docker build — команда подсистемы Docker, использующая файл Dockerfile и запускающая процесс создания образа.
В этом разделе рассказывается о том, как использовать файлы Dockerfile с контейнерами Windows, а также объясняются наиболее распространенные инструкции и базовый синтаксис таких файлов.
Здесь также рассматривается концепция образов контейнеров и их слоев. Дополнительные сведения об образах и их слоях см. в документации по базовым образам контейнеров.
Базовый синтаксис
В исходной форме файл Dockerfile может быть очень простым. Следующий пример создает образ, включающий IIS и сайт «hello world». Этот пример включает комментарии (обозначенные с помощью # ), поясняющие каждый шаг. В последующих разделах этой статьи более подробно рассматриваются правила синтаксиса Dockerfile и инструкции Dockerfile.
Файл Dockerfile необходимо создавать без расширения. Чтобы сделать это в Windows, создайте файл с помощью удобного для вас редактора, а затем сохраните его, используя нотацию «Dockerfile» (вместе с кавычками).
Дополнительные примеры файлов Dockerfile для Windows см. в репозитории файлов Dockerfile для Windows.
Instructions
Инструкции Dockerfile дают подсистеме Docker необходимые указания для создания образа контейнера. Эти инструкции выполняются по очереди, одна за другой. Ниже приведены примеры наиболее часто используемых инструкций в файлах Dockerfile. Полный список инструкций Dockerfile см. в справочнике по файлам Dockerfile.
Инструкция FROM задает образ контейнера, который будет применяться при создании нового образа. Например, при использовании инструкции FROM mcr.microsoft.com/windows/servercore полученный образ является производным и зависимым от базового образа ОС Windows Server Core. Если указанный образ отсутствует в системе, где выполняется процесс сборки Docker, подсистема Docker попытается скачать его из общедоступного или частного реестра образов.
Формат инструкции FROM выглядит следующим образом:
Ниже приведен пример команды FROM.
Чтобы загрузить Windows Server Core версии ltsc2019 из Реестра контейнеров (Майкрософт):
ВЫПОЛНИТЬ
Инструкция RUN задает команды, которые следует выполнить и поместить в новый образ контейнера. Эти команды могут включать такие элементы, как установка программного обеспечения, создание файлов и папок, а также создание конфигурации среды.
Инструкция RUN выглядит следующим образом:
Ниже приведен пример формы исполняемого файла.
Полученный образ выполняет команду powershell New-Item c:/test :
В отличие от предыдущего примера здесь та же операция выполняется с использованием формы оболочки:
Рекомендации по использованию инструкции RUN с Windows
В Windows при использовании инструкции RUN в формате исполняемого файла необходимо экранировать инструкции символы обратной косой черты.
Примеры использования инструкции RUN с Windows
В следующем примере для установки служб IIS в образе контейнера используется система DISM.
КОПИРОВАТЬ
Инструкция COPY копирует файлы и каталоги в файловую систему контейнера. Эти файлы и каталоги должны иметь путь, являющийся относительным для Dockerfile.
Формат инструкции COPY выглядит следующим образом:
Если источник или назначение содержит пробел, заключите путь в квадратные скобки и двойные кавычки, как показано в следующем примере:
Рекомендации по использованию инструкции COPY с Windows
При этом следующий формат с обратными косыми чертами работать не будет:
Примеры использования инструкции COPY с Windows
В следующем примере содержимое исходного каталога добавляется в каталог с именем sqllite в образе контейнера.
В следующем примере все файлы, начинающиеся с config, добавляют в каталог c:\temp образа контейнера.
Дополнительные сведения об инструкции COPY см. в справочнике по инструкции COPY.
Инструкция ADD похожа на инструкцию COPY, но с дополнительными возможностями. Кроме копирования файлов с узла в образ контейнера, инструкция ADD также позволяет скопировать файлы из удаленного расположения с помощью задания URL-адреса.
Формат инструкции ADD выглядит следующим образом:
Если источник или назначение содержит пробел, заключите путь в квадратные скобки и двойные кавычки.
Рекомендации по выполнению инструкции ADD с Windows
При этом следующий формат с обратными косыми чертами работать не будет:
Кроме того, в системе Linux во время копирования инструкция ADD распаковывает сжатые пакеты. В Windows эта функция недоступна.
Примеры использования инструкции ADD с Windows
В следующем примере содержимое исходного каталога добавляется в каталог с именем sqllite в образе контейнера.
В следующем примере все файлы, начинающиеся с «config», добавляют в каталог c:\temp образа контейнера.
В этом примере Python для Windows скачивается в каталог c:\temp образа контейнера.
Дополнительные сведения об инструкции ADD см. в справочнике по инструкции ADD.
WORKDIR
Формат инструкции WORKDIR выглядит следующим образом:
Рекомендации по использованию инструкции WORKDIR с Windows
Если в Windows рабочий каталог содержит обратную косую черту, ее следует экранировать.
Примеры
Подробные сведения об инструкции WORKDIR см. в справочнике по WORKDIR.
Формат инструкции CMD выглядит следующим образом:
Рекомендации по использованию инструкции CMD с Windows
Однако следующий формат без соответствующих косых черт работать не будет:
Дополнительные сведения об инструкции CMD см. в справочнике по инструкции CMD.
Escape-символ
Во многих случаях инструкция Dockerfile должна занимать несколько строк. Для этого можно использовать escape-символ. Escape-символ Dockerfile по умолчанию — обратная косая черта ( \ ). Однако, поскольку обратная косая черта также является разделителем пути к файлу в Windows, использование его для разделения нескольких строк может вызвать проблемы. Чтобы их избежать, можно изменить escape-символ по умолчанию с помощью директивы анализатора. Дополнительные сведения о директивах анализатора см. в этом разделе.
В следующем примере показана инструкция RUN, которая занимает несколько строк и использует escape-символ по умолчанию.
Чтобы изменить escape-символ, поместите директиву Parser для escape-символа на первую строку Dockerfile. Это показано в следующем примере.
Дополнительные сведения о директиве анализатора для escape-символа см. в этом разделе.
PowerShell в Dockerfile
Командлеты PowerShell
Вызовы REST
Invoke-WebRequest также работает на сервере Nano Server.
Сейчас Nano Server не поддерживает WebClient.
Сценарии PowerShell
В некоторых случаях удобно скопировать крипт в контейнеры, используемые при создании образа, и затем запустить его из контейнера.
Это ограничивает возможности кэширования слоев образов, а также ухудшает удобочитаемость файла Dockerfile.
Команда Docker build
После создания файла Dockerfile и сохранения его на диск можно запустить docker build для создания нового образа. Команда docker build принимает несколько необязательных параметров и путь к файлу Dockerfile. Полную документацию по команде Docker build, включая список всех параметров сборки, см. в справочнике по сборке.
Формат команды docker build выглядит следующим образом:
Например, следующая команда создает образ с именем «iis».
При инициации процесса сборки в выходных данных указывается состояние и выводятся все возникающие ошибки.
В результате создается новый образ контейнера, который в этом примере носит имя «iis».
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:
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’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:
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:
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’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’s format goes like this:
Considerations for using CMD with Windows
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
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.
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
Invoke-WebRequest also works in Nano Server.
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.»
How to run dockerfile
Copy raw contents
Dockerfile и коммуникация между контейнерами
В прошлой статье мы рассказали, что такое Docker и как с его помощью можно обойти Vendor–lock. В этой статье мы поговорим о Dockerfile как о правильном способе подготовки образов для Docker. Также мы рассмотрим ситуацию, когда контейнерам нужно взаимодействовать друг с другом.
В InfoboxCloud мы сделали готовый образ Ubuntu 14.04 с Docker. Не забудьте поставить галочку «Разрешить управление ядром ОС» при создании сервера, это требуется для работы Docker.
Dockerfile
Подход docker commit, описанный в предыдущей статье, не является рекомендованным для Docker. Его плюс состоит в том, что мы настраиваем контейнер практически так, как привыкли настраивать стандартный сервер.
Вместо этого подхода мы рекомендуем использовать подход Dockerfile и команду docker build. Dockerfile использует обычный DSL с инструкциями для построения образов Docker. После этого выполняется команда docker build для построения нового образа с инструкциями в Dockerfile.
Написание Dockerfile
Давайте создадим простой образ с веб-сервером с помощью Dockerfile. Для начала создадим директорию и сам Dockerfile.
Созданная директория — билд-окружение, в которой Docker вызывает контекст или строит контекст. Docker загрузит контекст в папке в процессе работы Docker–демона, когда будет запущена сборка образа. Таким образом будет возможно для Docker–демона получить доступ к любому коду, файлам или другим данным, которые вы захотите включить в образ.
Добавим в Dockerfile информацию по построению образа:
Dockerfile содержит набор инструкций с аргументами. Каждая инструкция пишется заглавными буквами (например FROM). Инструкции обрабатываются сверху вниз. Каждая инструкция добавляет новый слой в образ и коммитит изменения. Docker исполняет инструкции, следуя процессу:
Это означает, что если исполнение Dockerfile остановится по какой-то причине (например инструкция не сможет завершиться), вы сможете использовать образ до этой стадии. Это очень полезно при отладке: вы можете запустить контейнер из образа интерактивно и узнать, почему инструкция не выполнилась, используя последний созданный образ.
Также Dockerfile поддерживает комментарии. Любая строчка, начинающаяся с # означает комментарий.
Первая инструкция в Dockerfile всегда должна быть FROM, указывающая, из какого образа нужно построить образ. В нашем примере мы строим образ из базового образа ubuntu версии 14:04.
Далее мы указываем инструкцию MAINTAINER, сообщающую Docker автора образа и его email. Это полезно, чтобы пользователи образа могли связаться с автором при необходимости.
Инструкция RUN исполняет команду в конкретном образе. В нашем примере с помощью ее мы обновляем APT репозитории и устанавливаем пакет с NGINX, затем создаем файл /usr/share/nginx/html/index.html.
Мы используем этот формат для указания массива, содержащего команду для исполнения и параметры команды.
Далее мы указываем инструкцию EXPOSE, которая говорит Docker, что приложение в контейнере должно использовать определенный порт в контейнере. Это не означает, что вы можете автоматически получать доступ к сервису, запущенному на порту контейнера (в нашем примере порт 80). По соображениям безопасности Docker не открывает порт автоматически, но ожидает, когда это сделает пользователь в команде docker run. Вы можете указать множество инструкций EXPOSE для указания, какие порты должны быть открыты. Также инструкция EXPOSE полезна для проброса портов между контейнерами.
Строим образ из нашего файла
, где trukhinyuri – название репозитория, где будет храниться образ, nginx – имя образа. Последний параметр — путь к папке с Dockerfile. Если вы не укажете название образа, он автоматически получит название latest. Также вы можете указать git репозиторий, где находится Dockerfile.
В данном примере мы строим образ из Dockerfile, расположенном в корневой директории Docker.
Что произойдет, если инструкция не исполнится?
Давайте переименуем в Dockerfile nginx в ngin и посмотрим.
Использования кеша сборок для шаблонизации
Используя кеш сборок можно строить образы из Dockerfile в форме простых шаблонов. Например шаблон для обновления APT-кеша в Ubuntu:
Инструкция ENV устанавливает переменные окружения в образе. В данном случае мы указываем, когда шаблон был обновлен. Когда необходимо обновить построенный образ, просто нужно изменить дату в ENV. Docker сбросит кеш и версии пакетов в образе будут последними.
Инструкции Dockerfile
Давайте рассмотрим и другие инструкции Dockerfile. Полный список можно посмотреть тут.
CMD
Инструкция CMD указывает, какую команду необходимо запустить, когда контейнер запущен. В отличие от команды RUN указанная команда исполняется не во время построения образа, а во время запуска контейнера.
ENTRYPOINT
Часто команду CMD путают с ENTRYPOINT. Разница в том, что вы не можете перегружать ENTRYPOINT при запуске контейнера.
При запуске контейнера параметры передаются команде, указанной в ENTRYPOINT.
Можно комбинировать ENTRYPOINT и CMD.
WORKDIR
С помощью WORKDIR можно установить рабочую директорию, откуда будут запускаться команды ENTRYPOINT и CMD.
USER
Специфицирует пользователя, под которым должен быть запущен образ. Мы можем указать имя пользователя или UID и группу или GID.
VOLUME
Инструкция VOLUME добавляет тома в образ. Том — папка в одном или более контейнерах или папка хоста, проброшенная через Union File System (UFS).
Тома могут быть расшарены или повторно использованы между контейнерами. Это позволяет добавлять и изменять данные без коммита в образ.
В примере выше создается точка монтирования /opt/project для любого контейнера, созданного из образа. Таким образом вы можете указывать и несколько томов в массиве.
ADD
Инструкция ADD добавляет файлы или папки из нашего билд-окружения в образ, что полезно например при установке приложения.
Источником может быть URL, имя файла или директория.
В последнем примере архив tar.gz будет распакован в /var/www/wordpress. Если путь назначения не указан — будет использован полный путь включая директории.
COPY
Инструкция COPY отличается от ADD тем, что предназначена для копирования локальных файлов из билд-контекста и не поддерживает распаковки файлов:
ONBUILD
Инструкция ONBUILD добавляет триггеры в образы. Триггер исполняется, когда образ используется как базовый для другого образа, например, когда исходный код, нужный для образа еще не доступен, но требует для работы конкретного окружения.
Коммуникация между контейнерами
В предыдущей статье было показано, как запускать изолированные контейнеры Docker и как пробрасывать файловую систему в них. Но что, если приложениям нужно связываться друг с другом. Есть 2 способа: связь через проброс портов и линковку контейнеров.
Проброс портов
Такой способ связи уже был показан ранее. Посмотрим на варианты проброса портов чуть шире.
Когда мы используем EXPOSE в Dockerfile или параметр -p номер_порта – порт контейнера привязывается к произвольному порту хоста. Посмотреть этот порт можно командой docker ps или docker port имя_контейнера номер_порта_в_контейнере. В момент создания образа мы можем не знать, какой порт будет свободен на машине в момент запуска контейнера.
Можно привязать UDP порты, указав /udp:
Линковка контейнеров
Связь через сетевые порты — лишь один способ коммуникации. Docker предоставляет систему линковки, позволяющую связать множество контейнеров вместе и отправлять информацию о соединении от одного контейнера другому.
Что на самом деле происходит при линковке? Создается контейнер, который предоставляет информацию о себе контейнеру-получателю. Это происходит двумя способами:
Переменные окружения можно посмотреть, выполнив команду env:
Префикс DB_ был взят из alias контейнера.
Можно просто использовать информацию из hosts, например команда ping db (где db – alias) будет работать.
Источники информации:
- http://vegibit.com/how-to-use-a-dockerfile/
- http://docs.microsoft.com/ru-ru/virtualization/windowscontainers/manage-docker/manage-windows-dockerfile
- http://docs.microsoft.com/en-us/virtualization/windowscontainers/manage-docker/manage-windows-dockerfile
- http://github.com/hightemp/docLinux/blob/master/articles/Dockerfile%20%D0%B8%20%D0%BA%D0%BE%D0%BC%D0%BC%D1%83%D0%BD%D0%B8%D0%BA%D0%B0%D1%86%D0%B8%D1%8F%20%D0%BC%D0%B5%D0%B6%D0%B4%D1%83%20%D0%BA%D0%BE%D0%BD%D1%82%D0%B5%D0%B9%D0%BD%D0%B5%D1%80%D0%B0%D0%BC%D0%B8.md