В прошлом я имел дело с использованием Docker для агента сборки Azure DevOps Linux в посте « Настройка агента VSTS Linux с Docker за считанные минуты» , и я писал о том, как использовать Docker внутри определения сборки, чтобы иметь некоторые предварительные условия. для тестирования (например, MongoDB и SQL Server). Теперь пришло время сделать шаг вперед и использовать Docker.
Вам также может понравиться:
Руководство разработчика по Docker — Docker Compose
Использование команд Docker в определении конвейера хорошо, но у него есть некоторые недостатки: во- первых, этот подход страдает с точки зрения скорости выполнения, поскольку контейнер должен запускаться каждый раз, когда вы запускаете сборку (и должен останавливаться в конце сборки ). Действительно, если образ Docker уже присутствует в агенте, время запуска компьютера не так велико, но некоторые образы, такие как MsSQL, работают не сразу, поэтому вам нужно подождать, пока они будут готовы. за каждую сборку . Альтернативой является оставить их запущенными, даже если сборка завершена, но это может привести к исчерпанию ресурсов.
Другая проблема — это зависимость от движка Docker. Если я включу команды Docker в определение сборки, я могу строить только на машине, на которой установлен Docker. Если в большинстве моих проектов используются MongoDB, MsSQL и Redis, я могу просто установить все три на моей машине сборки, используя быстрый SSD в качестве хранилища. В этом сценарии я ожидаю использовать свои физические экземпляры, а не ждать, пока Docker раскрутит новый контейнер.
Включение команд Docker в определение конвейера — это хорошо, но это связывает конвейер с Docker и может сказаться на скорости выполнения.
То, что я хотел бы сделать, это использовать Docker для раскрутки агента и всех необходимых зависимостей одновременно. Затем мы используем этот агент со стандартной сборкой, для которой не требуется Docker. Это дает мне гибкость настройки машины для сборки со всем предустановленным или просто использовать Docker для раскрутки в считанные секунды агента, который может собрать мой код. Удаление зависимости Docker из моего определения конвейера дало пользователю максимальную гибкость.
Для моего первого эксперимента я также хочу использовать Docker в Windows 2109 для использования контейнера Windows.
First of all, you can read the nice MSDN article about how to create a Windows Docker image that downloads, install and run an agent inside a Windows server machine with Docker for Windows. This allows you to spin out a new Docker Agent based on Windows image in minutes (just the time to download and configure the agent).
Thanks to Windows Containers, running an Azure DevOps agent based on Windows is a simple Docker Run command.
Now, I need that agent to be able to use MongoDB and MsSQL to run integration tests. Clearly, I can install both DB engines on my host machine and let the Docker agent use them, but since I’ve already used my agent in Docker, I wish for my dependencies to also run in Docker. So, welcome Docker Compose!
Thanks to Docker Compose, I can define a YAML file with a list of images that are part of a single scenario, so I specified an agent image followed by a SQL Server and MongoDB images. The beauty of Docker Compose is the ability to refer to other container machines by name. Let’s do an example; here is my complete Docker compose YAML file.
version'2.4'
services
agent
image dockeragent latest
environment
AZP_TOKEN=efk5g3j344xfizar12duju65r34llyw4n7707r17h1$36o6pxsa4q
AZP_AGENT_NAME=mydockeragent
AZP_URL=https://dev.azure.com/gianmariaricci
NSTORE_MONGODB=mongodb://mongo/nstoretest
NSTORE_MSSQL=Server=mssql;user id=sa;password=sqlPw3$secure
mssql
image mssqlon2019 latest
environment
sa_password=sqlPw3$secure
ACCEPT_EULA=Y
ports
"1433:1433"
mongo
platform linux
image mongo
ports
"27017:27017"
To simplify everything, all of my integration tests that needs a connection string to MsSQL or MongoDB grab the connection string by the environment variable. This is convenient so each developer can use their DB instances of choice, but also, this technique makes it super easy to configure a Docker agent, specifying database connection strings as seen in Figure 1. I can specify in environment variables connection string to use for testing and I can simply use other Docker service names directly in the connection string.
As you can see (1), connection strings refer to other containers by name, nothing could be easier.
The real advantage of using Docker Compose is the ability to include Docker Compose file (as well as dockerfiles for all custom images that you could need) inside your source code. With this approach, you can specify build pipelines leveraging YAML build of Azure DevOps and also the configuration of the agent with all dependencies.
Since you can configure as many agents as you want for Azure DevOps (you actually pay for the number of concurrent executing pipelines), thanks to Docker Compose you can set up an agent suitable for your project in less than one minute. But this is optional, if you would not like to use Docker Compose, you can simply set up an agent manually, just as you did before.
Including a Docker Compose file in your source code allows the consumer of the code to start a compatible agent with a single command.
Thanks to Docker Compose, you pay the price of downloading pulling images once. You are paying only once the time needed for any image to become operative (like MsSQL or other databases that need a little bit before being able to satisfy requests). After everything is up and running, your agent is operative and can immediately run your standard builds — no Docker reference inside your YAML build file, no time wasted waiting for your images to become operational.
Thanks to the experimental feature of Windows Server 2019, I was able to specify a docker-compose file that contains not only windows images, but also Linux images. The only problem I had is that I did not find a Windows 2019 Image for the SQL Server. I started getting an error using standard MsSQL images (built for Windows 2016). So, I decided to download the official Docker file, change the reference image, and recreate the image, and everything worked like a charm!
Since it is used only for tests, I'm pretty confident that it should work, and indeed, my build runs just fine.
Actually, my agent created with Docker Compose is absolutely equal to all other agents. From the point of view of Azure DevOps, nothing is different, but I've started it with a single line of Docker-Compose command.
That's all, with a little effort, I'm able to include in my source code from both the YAML build definition as YAML Docker Compose file to specify the agent with all prerequisites to run the build. This is especially useful for open-source projects where you want to fork a project then activate CI with no effort.