How to use docker compose

How to use docker compose

Настройка cервера с помощью docker для простых проектов. Часть вторая: docker-compose

How to use docker compose. Смотреть фото How to use docker compose. Смотреть картинку How to use docker compose. Картинка про How to use docker compose. Фото How to use docker compose

Мы продолжаем цикл обучающих статей для начинающих системных администраторов: если вы являетесь опытным админом, можете смело пропустить этот материал. В этой статье мы разберем docker-compose.

Итак, в этой статьей рассмотрим следующие пункты:

Чем удобен docker-compose?

Приступаем к написанию yml-файла.

Пункт 1. Указание версии.

Пункт 2. Объявляем сервисы.

Пункт 3. Объявляем контейнеры.

Пункт 4. Локальная сеть контейнеров.

Пункт 4.1. Основные конфигурации и ключи файла docker-compose.

Пункт 5. Пишем nginx.

Пункт 6. Пишем php-fpm.

Пункт 7. Пишем mysql.

Пункт 8. Общий итог docker-compose.yml.

docker-compose.

Чем удобен docker-compose?

Установка.

Для начала установим инструмент. Загружаем текущую стабильную версию:

Делаем скачанный файл исполняемым:

Все установлено и работает.

Подготовка:

Какие сервисы понадобятся?

База данных: mysql.

Первым делом подготовим директории для работы. Для начала создадим директорию, где будет лежать docker-compose.yml. Мы приняли за стандарт, что в нашей компании все файлы docker-compose находится в директории /var/apps/. Создаем директорию и переходим в нее:

Создаем директорию проекта:

Создаем файл docker-compose.yml:

Теперь создадим директорию где будут хранится наши конфигурационные файлы площадок, конфигурации php.ini и так далее:

Давайте заранее создадим все директории и конфигурации наших сервисов:

Получилась такая структура директорий:

volumes/ (директория с конфигурационным файлами)

build/ (директория c Dockerfile для наших контейнеров)

etc/ (директория с конфигурационными файлами для наших сервисов)

How to use docker compose. Смотреть фото How to use docker compose. Смотреть картинку How to use docker compose. Картинка про How to use docker compose. Фото How to use docker compose

Перед дальнейшими работами очистим все образы, собранные ранее в предыдущей статье. Для этого действия подойдет команда:

Смотрим запущенные контейнеры:

Для остановки всех контейнеров можно использовать команду:

Все контейнеры и образы были удалены с сервера.

Базовая настройка завершена.

Приступаем к написанию нашего yml-файла.

How to use docker compose. Смотреть фото How to use docker compose. Смотреть картинку How to use docker compose. Картинка про How to use docker compose. Фото How to use docker compose

Итак, открываем docker-compose.yml.

Пункт 1. Указание версии.

Для ознакомления со всеми версиями, и для чего они нужны, можете перейти на официальный мануал по этому поводу: version.

Пункт 2. Объявляем сервисы.

Мы объявляем, что далее будут идти наши контейнеры.

Пункт 3. Объявляем наши контейнеры.

Не забываем про формат yml, поэтому делаем два пробела и добавляем:

Выглядит это так:

Пункт 4: Локальная сеть контейнеров.

Давайте заранее обьявим нашу сеть, чтобы больше к ней не возвращаться. За сеть у нас отвечает ключ networks.

Добавляем такие строки:

Пункт 4.5. Основные конфигурации и ключи нашего файла docker-compose.

Для чего необходимо пробрасывать директории в контейнер? Каждый раз, когда мы будем пересобирать контейнер, у нас будут удаляться все внутренние директории. Для того, чтобы это не происходило, мы пробрасываем директорию в контейнер. После чего все файлы будут храниться на хост-машине, и после того, как будет пересобран контейнер, файлы будут в целости и сохранности.

Например: У нас имеется mysql в контейнере. Если мы не пробросим директорию с БД, то все наши БД буду удалены после того, как мы пересоберем контейнер. Поэтому для всех сервисов лучше всего пробрасывать все нужные директории. Это важно!

Пункт 5. Пишем nginx.

Переходим к строчке nginx и делаем отступ 4 пробела. Формат yml (да, не устану это повторять:)).

Указываем название контейнера container_name:

Указываем hostname:

Указываем местонахождение нашего Dockerfile для сборки build:

Указываем директории, которые необходимо прокинуть в контейнер с помощью volumes. Обязательно необходимо прокинуть:

Файлы площадки. Для работы со статикой.

Конфигурацию nginx. Для быстрого управление в случае необходимости.

Конфигурационные файлы площадки. Для работы площадки.

Директорию с сертификатами ssl. Для быстрого подключения работы по https.

Директорию с log-файлом nginx. Для удобства анализа в дальнейшем.

Указываем volumes и прокидываем директории через дефис:

Ключ :ro означает read only. Он добавлен для безопасности, чтобы внутри контейнера нельзя было изменить конфигурационные файлы.

Указываем порты ports:

Открываем порты 80 и 443 на хосте и пробрасываем их в контейнер.

Указываем приоритет загрузки links:

Контейнер nginx не будет загружен быстрее чем контейнер с php-fpm. Делается для того, чтоб пользователя не видели 502 код ответа, в случае перегрузки контейнеров.

Указываем как часто можно перезагружаться контейнеру в случае ошибки:

Присваиваем ip адрес контейнеру с помощью networks:

В итоге получается у так:

У нас имеется контейнер nginx:

С названием DOMAIN_NAME-nginx

hostname в контейнере DOMAIN_NAME-nginx

Собирающийся из нашего Dockerfile по адресу ./volumes/build/nginx

Работающий на 80 и 443 портах хост машины

Запускающийся только после контейнера php-fpm

Часто перезагружаемый в случае ошибки и с ip адресом 172.16.1.4.

Пункт 6. Пишем php-fpm.

Переходим к строке php-fpm.

Название:

Hostname:

Расположение Dockerfile:

Приоритет загрузки links: указывать не нужно.

Порты:

Директории, которые нужно прокинуть:

php.ini для быстрого изменения конфигурации (в случае необходимости).

Конфигурационный файл площадки.

IP адрес:

Добавляем права на все изменения в докере php:

Для чего это нужно? Например php-fpm необходимо будет сменить приоритет процесса. Если данная строка будет отсутствовать, то получим ошибку:

mbind: Operation not permitted

Или, например, площадка у нас работает от пользователя DOMAIN_NAME. Для того, чтобы площадка работала в контейнере, php-fpm необходимо добавить пользователя в систему. Если строки не будет, то будет выдаваться аналогичная ошибка.

Перезагрузка контейнера:

У нас имеется контейнер php-fpm:

С названием DOMAIN_NAME-php-fpm;

hostname в контейнере DOMAIN_NAME-php-fpm;

Работающий на 9000 порте хост машины;

Часто перезагружаемый в случае ошибки и с ip адресом 172.16.1.5.

Пункт 7. Пишем mysql.

Переходим к строке mysql.

Название:

Hostname:

Расположение Dockerfile:

Приоритет загрузки links: указывать не нужно.

Порты:

Директории, которые нужно прокинуть:

Директория для хранения БД.

Конфигурационный файл mysql.

IP адрес:

Перезагрузка контейнера:

У нас имеется контейнер mysql:

С названием DOMAIN_NAME-mysql;

hostname в контейнере DOMAIN_NAME-mysql;

Собирающийся из нашего Dockerfile по адресу ./volumes/build/mysql;

Работающий на 3010 порте хост машины;

Часто перезагружаемый в случае ошибки и ip адресом 172.16.1.6.

Пункт 8. Общий итог нашего docker-compose.yml:

Итак, мы разобрали базовые ключи и команды для написание docker-compose. Теперь вы можете самостоятельно писать yml, а самое главное понимать, что именно вы написали! Но перед запуском необходимо написать Dockerfile, и в следующей статье мы с вами разберем, что это такое, для чего Dockerfile нужен, и как его красиво писать. После чего запустим наш docker-compose, накатим WordPress и проверим его работу.

Docker Compose: от разработки до продакшена

Перевод транскрипции подкаста подготовлен в преддверии старта курса «Администратор Linux»

How to use docker compose. Смотреть фото How to use docker compose. Смотреть картинку How to use docker compose. Картинка про How to use docker compose. Фото How to use docker compose

Docker Compose — это удивительный инструмент для создания рабочего
окружения для стека, используемого в вашем приложении. Он позволяет вам определять
каждый компонент вашего приложения, следуя четкому и простому синтаксису в YAML-
файлах.

С появлением docker compose v3 эти YAML-файлы могут использоваться непосредственно в рабочей среде, при работе с кластером Docker Swarm.

Но значит ли это, что вы можете использовать один и тот же docker-compose файл в процессе разработки и в продакшен среде? Или использовать этот же файл для стейджинга? Ну, в целом — да, но для такого функционала нам необходимо следующее:

Различия между файлами для разработки и продакшена

Во время разработки вы, скорее всего, захотите проверять изменения кода в
режиме реального времени. Для этого, обычно, том с исходным кодом монтируется в
контейнер, в котором находится рантайм для вашего приложения. Но для продакшн-среды
такой способ не подходит.

В продакшене у вас есть кластер с множеством узлов, а том является локальным по
отношению к узлу, на котором работает ваш контейнер (или сервис), поэтому вы не
можете монтировать исходный код без сложных операций, которые включают в себя
синхронизацию кода, сигналы и т. д.

Вместо этого мы, обычно, хотим создать образ с конкретной версией вашего кода.
Его принято помечать соответствующим тегом (можно использовать семантическое
версионирование или другую систему на ваше усмотрение).

Переопределение конфигурации

Учитывая различия и то, что ваши зависимости могут отличаться в сценариях
разработки и продакшена, ясно, что нам потребуются разные конфигурационные файлы.

Docker compose поддерживает объединение различных compose-файлов для
получения окончательной конфигурации. Как это работает можно увидеть на примере:

Как было сказано, docker compose поддерживает объединение нескольких compose-
файлов, это позволяет переопределять различные параметры во втором файле. Например:

Такой синтаксис не очень удобен в процессе разработки, когда команду
понадобится выполнять множество раз.

К счастью, docker compose автоматически ищет специальный файл с именем
docker-compose.override.yml для переопределения значений docker-compose.yml. Если
переименовать второй файл, то получится тот же результат, только с помощью изначальной команды:

Хорошо, так запомнить проще.

Интерполяция переменных

Файлы конфигурации поддерживают интерполяцию
переменных и значения по умолчанию. То есть вы можете сделать следующее:

И если вы выполняете docker-compose build (или push) без переменной окружения
$MY_SERVICE_VERSION, будет использовано значение latest, но если вы установите
значение переменной окружения до сборки, оно будет использовано при сборке или пуше
в регистр private.registry.mine.

Мои принципы

Подходы, которые удобны для меня, могут пригодиться и вам. Я следую этим
простым правилам:

Давайте посмотрим на простой пример.

Я могу использовать docker-compose (docker-compose up), чтобы запустить стек в
режиме разработки с исходным кодом, смонтированным в /project/src.

Я могу использовать эти же файлы на продакшене! И я мог бы использовать точно
такой же файл docker-compose.yml для стейджинга. Чтобы развернуть это на
продакшен, мне просто нужно собрать и отправить образ с предопределенным тегом
на этапе CI:

На продакшене это можно запустить с помощью следующих команд:

И если вы хотите сделать то же самое на стейдже, необходимо просто определить
необходимые переменные окружения для работы в среде стейджинга:

В итоге мы использовали два разных docker-compose файла, которые без
дублирования конфигураций могут использоваться для любой вашей среды!

Узнать подробнее о курсе «Администратор Linux»

Шпаргалка по работе с docker-compose

В данной инструкции мы приведем различные примеры по работе с docker-compose без подробного описания принципа работы. Данный материал можно использовать в качестве шпаргалки.

Базовый шаблон

В первую очередь, предлагаю заготовку для docker-compose файла, на основе которой можно начинать писать свой сценарий для docker.

:
image:
container_name:
hostname:
restart: unless-stopped
environment:
TZ: «Europe/Moscow»
networks:
— default

networks:
default:
ipam:
driver: default
config:
— subnet: 172.28.0.0/16

Сервисы

В данном разделе рассмотрим примеры настроек сервисов (контейнеров). Синтаксис:

1. Создание контейнера из готового образа. Образ указывается с помощью директивы image:

* в данном примере будет взят образ nginx для поднятия контейнера.

2. Сборка контейнера из Dockerfile. Для этого используем опцию build:

3. Проброс папок (volumes). Настраивается с помощью опции volumes:

* в нашем примере мы смонтируем локальный каталог /data/mysql на хосте внутрь контейнера в качестве каталога /var/lib/mysql.

Также мы можем смонтировать папку только на чтение, например:

4. Работа с портами. С помощью опции ports мы можем указывать, на каких портах должен слушать контейнер и на какие порты должны пробрасываться запросы:

* в данном примере наш контейнер будет слушать запросы на порту 8080 и передавать их внутрь контейнера на порт 80.

5. Переменные окружения. В нашей универсальной заготовке мы уже использовали одну системную переменную:

environment:
TZ: «Europe/Moscow»

Чтобы передать несколько переменных, просто их перечисляем:

environment:
TZ: «Europe/Moscow»
MYSQL_ROOT_PASSWORD=password

Для каждого приложения есть свой набор системных переменных, которые оно понимает и интерпретирует. Например, MYSQL_ROOT_PASSWORD поймет СУБД и установит значение в качестве пароля для пользователя root.

6. Зависимости для контейнеров. Мы можем указать с помощью опции depends_on, от какого контейнера зависит сервис:

* в конкретном примере, контейнер не запустится, пока не поднимется db.

7. Переопределить команду. С помощью директивы command мы можем переопределить команду для запуска, например:

command: [ «redis-server», «/usr/local/etc/redis/redis.conf» ]

* в данном примере мы запустим redis-server с альтернативным конфигурационным файлом.

Или можно написать так:

command:
— redis-server
— /usr/local/etc/redis/redis.conf

8. Метки. С помощью опции labels мы можем указывать дополнительную информацию для ориентирования или фильтров при поиске контейнеров:

* данные могут быть произвольные. Обратите внимание, что в качестве значений мы указали переменные, которые можно просто передать из системного окружения.

9. Пользователь. Директива user позволяет задать конкретного пользователя, от которого будет запускаться и работать контейнер:

Healthcheck

Данная директива, хоть и является частью сервиса, мы рассмотрим ее в отдельном разделе. Синтаксис:

Tutorial: Deploy a multi-container group using Docker Compose

In this tutorial, you use Docker Compose to define and run a multi-container application locally and then deploy it as a container group in Azure Container Instances.

Run containers in Azure Container Instances on-demand when you develop cloud-native apps with Docker and you want to switch seamlessly from local development to cloud deployment. This capability is enabled by integration between Docker and Azure. You can use native Docker commands to run either a single container instance or multi-container group in Azure.

Not all features of Azure Container Instances are supported. Provide feedback about the Docker-Azure integration by creating an issue in the Docker ACI Integration GitHub repository.

You can use the Docker extension for Visual Studio Code for an integrated experience to develop, run, and manage containers, images, and contexts.

In this article, you:

Prerequisites

Create Azure container registry

Before you create your container registry, you need a resource group to deploy it to. A resource group is a logical collection into which all Azure resources are deployed and managed.

Create a resource group with the az group create command. In the following example, a resource group named myResourceGroup is created in the eastus region:

Once you’ve created the resource group, create an Azure container registry with the az acr create command. The container registry name must be unique within Azure, and contain 5-50 alphanumeric characters. Replace with a unique name for your registry:

Here’s partial output for a new Azure container registry named mycontainerregistry082:

Log in to container registry

You must log in to your Azure Container Registry instance before pushing images to it. Use the az acr login command to complete the operation. You must provide the unique name you chose for the container registry when you created it.

The command returns Login Succeeded once completed:

Get application code

The sample application used in this tutorial is a basic voting app. The application consists of a front-end web component and a back-end Redis instance. The web component is packaged into a custom container image. The Redis instance uses an unmodified image from Docker Hub.

Use git to clone the sample application to your development environment:

Change into the cloned directory.

Inside the directory is the application source code and a pre-created Docker compose file, docker-compose.yaml.

Modify Docker compose file

Open docker-compose.yaml in a text editor. The file configures the azure-vote-back and azure-vote-front services.

In the azure-vote-front configuration, make the following two changes:

The updated file should look similar to the following:

By making these substitutions, the azure-vote-front image you build in the next step is tagged for your Azure container registry, and the image can be pulled to run in Azure Container Instances.

You don’t have to use an Azure container registry for this scenario. For example, you could choose a private repository in Docker Hub to host your application image. If you choose a different registry, update the image property appropriately.

Run multi-container application locally

Run docker-compose up, which uses the sample docker-compose.yaml file to build the container image, download the Redis image, and start the application:

When completed, use the docker images command to see the created images. Three images have been downloaded or created. The azure-vote-front image contains the front-end application, which uses the uwsgi-nginx-flask image as a base. The redis image is used to start a Redis instance.

Run the docker ps command to see the running containers:

To see the running application, enter http://localhost:80 in a local web browser. The sample application loads, as shown in the following example:

How to use docker compose. Смотреть фото How to use docker compose. Смотреть картинку How to use docker compose. Картинка про How to use docker compose. Фото How to use docker compose

After trying the local application, run docker-compose down to stop the application and remove the containers.

Push image to container registry

To deploy the application to Azure Container Instances, you need to push the azure-vote-front image to your container registry. Run docker-compose push to push the image:

It can take a few minutes to push to the registry.

To verify the image is stored in your registry, run the az acr repository show command:

Create Azure context

To use Docker commands to run containers in Azure Container Instances, first log into Azure:

When prompted, enter or select your Azure credentials.

When prompted, select your Azure subscription ID, then select an existing resource group or create a new resource group. If you choose a new resource group, it’s created with a system-generated name. Azure container instances, like all Azure resources, must be deployed into a resource group. Resource groups allow you to organize and manage related Azure resources.

Run docker context ls to confirm that you added the ACI context to your Docker contexts:

Deploy application to Azure Container Instances

Next, change to the ACI context. Subsequent Docker commands run in this context.

Run docker compose up to start the application in Azure Container Instances. The azure-vote-front image is pulled from your container registry and the container group is created in Azure Container Instances.

In a short time, the container group is deployed. Sample output:

Run docker ps to see the running containers and the IP address assigned to the container group.

How to use docker compose. Смотреть фото How to use docker compose. Смотреть картинку How to use docker compose. Картинка про How to use docker compose. Фото How to use docker compose

To see the logs of the front-end container, run the docker logs command. For example:

You can also use the Azure portal or other Azure tools to see the properties and status of the container group you deployed.

When you finish trying the application, stop the application and containers with docker compose down :

This command deletes the container group in Azure Container Instances.

Next steps

In this tutorial, you used Docker Compose to switch from running a multi-container application locally to running in Azure Container Instances. You learned how to:

You can also use the Docker extension for Visual Studio Code for an integrated experience to develop, run, and manage containers, images, and contexts.

If you want to take advantage of more features in Azure Container Instances, use Azure tools to specify a multi-container group. For example, see the tutorials to deploy a container group using the Azure CLI with a YAML file, or deploy using an Azure Resource Manager template.

Use Docker Compose

Also, for single-container scenarios, using Docker Compose provides tool-independent configuration in a way that a single Dockerfile does not. Configuration settings such as volume mounts for the container, port mappings, and environment variables can be declared in the docker-compose YML files.

To use Docker Compose in VS Code using the Docker extension, you should already be familiar with the basics of Docker Compose.

Adding Docker Compose support to your project

If you already have one or more Dockerfiles, you can add Docker Compose files by opening the Command Palette ( ⇧⌘P (Windows, Linux Ctrl+Shift+P ) ), and using the Docker: Add Docker Compose Files to Workspace command. Follow the prompts.

You can add Docker Compose files to your workspace at the same time you add a Dockerfile by opening the Command Palette ( ⇧⌘P (Windows, Linux Ctrl+Shift+P ) ) and using the Docker: Add Docker Files to Workspace command. You’ll be asked if you want to add Docker Compose files. If you want to keep your existing Dockerfile, choose No when prompted to overwrite the Dockerfile.

The Docker extension adds the docker-compose.yml file to your workspace. This file contains the configuration to bring up the containers as expected in production. In some cases, a docker-compose.debug.yml is also generated. This file provides a simplified mode for starting that enables the debugger.

How to use docker compose. Смотреть фото How to use docker compose. Смотреть картинку How to use docker compose. Картинка про How to use docker compose. Фото How to use docker compose

The VS Code Docker extension generates files that work out of the box, but you can also customize them to optimize for your scenario. You can then use the Docker Compose Up command (right-click on the docker-compose.yml file, or find the command in the Command Palette) to get everything started at once. You can also use the docker-compose up command from the command prompt or terminal window in VS Code to start the containers. Refer to the Docker Compose documentation about how to configure the Docker Compose behavior and what command-line options are available.

Tip: When using Docker Compose, don’t specify a host port. Instead, let the Docker pick a random available port to automatically avoid port conflict issues.

Add new containers to your projects

If you want to add another app or service, you can run Add Docker Compose Files to Workspace again, and choose to overwrite the existing docker-compose files, but you’ll lose any customization in those files. If you want to preserve changes to the compose files, you can manually modify the docker-compose.yml file to add the new service. Typically, you can cut and paste the existing service section and change the names as appropriate for the new service.

You can run the Add Docker Files to Workspace command again to generate the Dockerfile for a new app. While each app or service has its own Dockerfile, there’s typically one docker-compose.yml and one docker-compose.debug.yml file per workspace.

Debug

First, refer to the debugging documentation for your target platform, to understand the basics on debugging in containers with VS Code:

If you want to debug in Docker Compose, run the command Docker Compose Up using one of the two Docker Compose files as described in the previous section, and then attach using the appropriate Attach launch configuration. Launching directly using the normal launch configuration does not use Docker Compose.

Node.js

On the Debug tab, choose the Configuration dropdown, choose New Configuration and select the Docker Attach configuration template Node.js Docker Attach (Preview).

How to use docker compose. Смотреть фото How to use docker compose. Смотреть картинку How to use docker compose. Картинка про How to use docker compose. Фото How to use docker compose

Right-click on the docker-compose.debug.yml file and choose Compose Up.

When you attach to a service that exposes an HTTP endpoint that returns HTML, the web browser doesn’t open automatically. To open the app in the browser, choose the container in the sidebar, right-click and choose Open in Browser. If multiple ports are configured, you’ll be asked to choose the port.

Python

For debugging Python with Docker Compose, follow these steps:

On the Debug tab, choose the Configuration dropdown, choose New Configuration, choose Python, and select the Remote Attach configuration template.

How to use docker compose. Смотреть фото How to use docker compose. Смотреть картинку How to use docker compose. Картинка про How to use docker compose. Фото How to use docker compose

Note: By default, when using Docker: Add Docker Files to Workspace, choosing the Django and Flask options will scaffold a Dockerfile configured for Gunicorn. Follow the instructions in the Python in a container quickstart to ensure it is configured properly before proceeding.

Right-click on the docker-compose.debug.yml file (example shown below) and choose Compose Up.

Once your container is built and running, attach the debugger by hitting F5 with the Python: Remote Attach launch configuration selected.

How to use docker compose. Смотреть фото How to use docker compose. Смотреть картинку How to use docker compose. Картинка про How to use docker compose. Фото How to use docker compose

Note: If you would like to import the Python debugger into a specific file, more information can be found in the debugpy README.

When you attach to a service that exposes an HTTP endpoint and returns HTML, the web browser may not open automatically. To open the app in the browser, right-click the container in the Docker Explorer and choose Open in Browser. If multiple ports are configured, you’ll be asked to choose the port.

How to use docker compose. Смотреть фото How to use docker compose. Смотреть картинку How to use docker compose. Картинка про How to use docker compose. Фото How to use docker compose

You’re now debugging your running app in the container.

On the Debug tab, choose the Configuration dropdown, choose New Configuration and select the Docker Attach configuration template .NET Core Docker Attach (Preview).

VS Code tries to copy vsdbg from the host machine to the target container using a default path. You can also provide a path to an existing instance of vsdbg in the Attach configuration.

Right-click on the docker-compose.debug.yml file and choose Compose Up.

When you attach to a service that exposes an HTTP endpoint that returns HTML, the web browser doesn’t open automatically. To open the app in the browser, choose the container in the sidebar, right-click and choose Open in Browser. If multiple ports are configured, you’ll be asked to choose the port.

How to use docker compose. Смотреть фото How to use docker compose. Смотреть картинку How to use docker compose. Картинка про How to use docker compose. Фото How to use docker compose

How to use docker compose. Смотреть фото How to use docker compose. Смотреть картинку How to use docker compose. Картинка про How to use docker compose. Фото How to use docker compose

To skip this step, specify the container name in the Attach configuration in launch.json:

Next, you’re asked if you want to copy the debugger ( vsdbg ) into the container. Choose Yes.

How to use docker compose. Смотреть фото How to use docker compose. Смотреть картинку How to use docker compose. Картинка про How to use docker compose. Фото How to use docker compose

How to use docker compose. Смотреть фото How to use docker compose. Смотреть картинку How to use docker compose. Картинка про How to use docker compose. Фото How to use docker compose

Volume mounts

Docker Compose with multiple Compose files

Workspaces can have multiple docker-compose files to handle different environments like development, test, and production. The content of the configuration can be split into multiple files. For example, a base compose file that defines the common information for all environments and separate override files that define environment-specific information. When these files are passed as input to the docker-compose command, it combines these files into a single configuration. By default, the Docker: Compose Up command passes a single file as input to the compose command, but you can customize the compose up command to pass in multiple files using command customization. Or, you can use a custom task to invoke the docker-compose command with the desired parameters.

Note: If your workspace has docker-compose.yml and docker-compose.override.yml and no other compose files, then the docker-compose command is invoked with no input files and it implicitly uses these files. In this case, no customization is needed.

Command customization

Command customization provides various ways to customize the compose up command based on your requirements. The following are few sample command customization for the compose up command.

Base file and an override file

Template matching

Let’s assume you have different set of input files for each environment. You could define multiple templates with regular expression match, and the selected file name will be matched against this match property and the corresponding template will be used.

Pick a template when the command is invoked

If you omit the match property from command templates, you will be asked which template to use each time compose up command is invoked. For example:

Custom tasks

Rather than use command customization, you can also define a task like the following to invoke a docker-compose command. Please refer custom task for more detail on this.

Источники информации:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *