Docker compose version что это
Перейти к содержимому

Docker compose version что это

  • автор:

Compose file versions and upgrading

The Compose file is a YAML file defining services, networks, and volumes for a Docker application.

The Compose file formats are now described in these references, specific to each version.

Reference file What changed in this version
Compose Specification (most current, and recommended) Versioning
Version 3 Version 3 updates
Version 2 Version 2 updates
Version 1 (Deprecated) Version 1 updates

The topics below explain the differences among the versions, Docker Engine compatibility, and how to upgrade.

Compatibility matrix

There are several versions of the Compose file format – 1, 2, 2.x, and 3.x

This table shows which Compose file versions support specific Docker releases.

Compose file format Docker Engine release
Compose specification 19.03.0+
3.8 19.03.0+
3.7 18.06.0+
3.6 18.02.0+
3.5 17.12.0+
3.4 17.09.0+
3.3 17.06.0+
3.2 17.04.0+
3.1 1.13.1+
3.0 1.13.0+
2.4 17.12.0+
2.3 17.06.0+
2.2 1.13.0+
2.1 1.12.0+
2.0 1.10.0+

In addition to Compose file format versions shown in the table, the Compose itself is on a release schedule, as shown in Compose releases, but file format versions do not necessarily increment with each release. For example, Compose file format 3.0 was first introduced in Compose release 1.10.0, and versioned gradually in subsequent releases.

The latest Compose file format is defined by the Compose Specification and is implemented by Docker Compose 1.27.0+.

Looking for more detail on Docker and Compose compatibility?

We recommend keeping up-to-date with newer releases as much as possible. However, if you are using an older version of Docker and want to determine which Compose release is compatible, refer to the Compose release notes. Each set of release notes gives details on which versions of Docker Engine are supported, along with compatible Compose file format versions. (See also, the discussion in issue #3404.)

For details on versions and how to upgrade, see Versioning and Upgrading.

Versioning

There are three legacy versions of the Compose file format:

Version 1. This is specified by omitting a version key at the root of the YAML.

Version 2.x. This is specified with a version: ‘2’ or version: ‘2.1’ , etc., entry at the root of the YAML.

Version 3.x, designed to be cross-compatible between Compose and the Docker Engine’s swarm mode. This is specified with a version: ‘3’ or version: ‘3.1’ , etc., entry at the root of the YAML.

The latest and recommended version of the Compose file format is defined by the Compose Specification. This format merges the 2.x and 3.x versions and is implemented by Compose 1.27.0+.

v2 and v3 Declaration

Note: When specifying the Compose file version to use, make sure to specify both the major and minor numbers. If no minor version is given, 0 is used by default and not the latest minor version.

The Compatibility Matrix shows Compose file versions mapped to Docker Engine releases.

To move your project to a later version, see the Upgrading section.

Note: If you’re using multiple Compose files or extending services, each file must be of the same version — you cannot, for example, mix version 1 and 2 in a single project.

Several things differ depending on which version you use:

  • The structure and permitted configuration keys
  • The minimum Docker Engine version you must be running
  • Compose’s behaviour with regards to networking

These differences are explained below.

Version 1 (Deprecated)

Compose files that do not declare a version are considered “version 1”. In those files, all the services are declared at the root of the document.

Version 1 is supported by Compose up to 1.6.x. It will be deprecated in a future Compose release.

Version 1 files cannot declare named volumes, networks or build arguments.

Compose does not take advantage of networking when you use version 1: every container is placed on the default bridge network and is reachable from every other container at its IP address. You need to use links to enable discovery between containers.

Version 2

Compose files using the version 2 syntax must indicate the version number at the root of the document. All services must be declared under the services key.

Version 2 files are supported by Compose 1.6.0+ and require a Docker Engine of version 1.10.0+.

Named volumes can be declared under the volumes key, and networks can be declared under the networks key.

By default, every container joins an application-wide default network, and is discoverable at a hostname that’s the same as the service name. This means links are largely unnecessary. For more details, see Networking in Compose.

Note

When specifying the Compose file version to use, make sure to specify both the major and minor numbers. If no minor version is given, 0 is used by default and not the latest minor version. As a result, features added in later versions will not be supported. For example:

Docker совет №25: Какую API версию docker compose использовать?

May 24, 2018 07:08 · 248 words · 2 minute read docker docker-compose

На сегодняшний день Docker Compose имеет 3 основные версии API (v1, v2 и v3). В зависимости от используемой версии вам могут быть доступны (или недоступны) некоторые полезные функции и возможности.

Наверняка вы обращали внимание, что в самом начале файла docker-compose.yml обычно присутствует строка version: ‘2’ или version: ‘3’ . Это и есть версия API Docker Compose!

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

Что касается второй и третьей версии API ( v2 / v3 ), то самая простая рекомендация — использовать самую последнюю (актуальную) версию, однако здесь уже нужно исходить из конкретных требований и особенностей вашего проекта. Например, если вы не можете (или не хотите) обойтись без конструкции volume_from , то третья версия API вам не подойдет, а если вы работаете с Docker Swarm, то нужно использовать только версию 3+.

Кроме того, в третьей версии API целая куча настроек использования CPU и памяти перенесена в свойство deploy . Полный список всех изменений и функционал версий v2 и v3 можно найти здесь.

Что касается исполняемого файла docker-compose , то его всегда нужно обновлять до последней актуальной версии — как минимум, они будут содержать исправление ошибок предыдущих версий.

На официальном сайте всегда можно просмотреть матрицу совместимости, чтобы узнать, совместима ли ваша версия API с конкретной бинарной версией docker-compose (да, это совершенно разные вещи).

Составление версий файлов и обновление

Файл Compose — это файл YAML , определяющий службы, сети и тома для приложения Docker.

Форматы файлов «Составь» теперь описываются в этих ссылках,специфичных для каждой версии.

Reference file Что изменилось в этой версии
Составление спецификации (самая актуальная и рекомендуемая) Versioning
Version 3 Обновления версии 3
Version 2 Обновления версии 2
Версия 1 (устаревшая) Обновления версии 1

В разделах ниже объясняются различия между версиями, совместимость с Docker Engine и способы обновления .

Compatibility matrix

Существует несколько версий формата файла Compose-1,2,2.x и 3.x.

В этой таблице показано,какие версии файлов Compose поддерживают определенные выпуски Docker’а.

Составьте формат файла Релиз Docker Engine
Compose specification 19.03.0+
3.8 19.03.0+
3.7 18.06.0+
3.6 18.02.0+
3.5 17.12.0+
3.4 17.09.0+
3.3 17.06.0+
3.2 17.04.0+
3.1 1.13.1+
3.0 1.13.0+
2.4 17.12.0+
2.3 17.06.0+
2.2 1.13.0+
2.1 1.12.0+
2.0 1.10.0+

В дополнение к версиям формата файла Compose, показанным в таблице, сама Compose находится в расписании выпуска, как показано в выпусках Compose , но версии формата файла не обязательно увеличиваются с каждым выпуском. Например, формат файлов Compose 3.0 был впервые представлен в версии 1.10.0 Compose и постепенно обновлялся в последующих выпусках.

Последний формат файла Compose определяется спецификацией Compose и реализуется Docker Compose 1.27.0+ .

Ищете более подробную информацию о совместимости Docker и Compose?

Мы рекомендуем быть в курсе последних выпусков, насколько это возможно. Однако, если вы используете более старую версию Docker и хотите определить, какой выпуск Compose совместим, обратитесь к примечаниям к выпуску Compose . Каждый набор примечаний к выпуску содержит подробности о том, какие версии Docker Engine поддерживаются, а также о совместимых версиях формата файлов Compose. (См. Также обсуждение в выпуске № 3404. )

Дополнительные сведения о версиях и способах обновления см . в разделе Управление версиями и обновление .

Versioning

Существует три устаревшие версии формата файла Compose:

Версия 1. Это указывается путем исключения ключа version

Версия 2.х. Это указывается с version: ‘2’ или version: ‘2.1’ и т. Д., Записью в корне YAML.

Версия 3.x, предназначенная для перекрестной совместимости между Compose и режимом роя Docker Engine . Это указывается version: ‘3’ или version: ‘3.1’ и т. д., записью в корне YAML.

Последняя и рекомендуемая версия формата файла Compose определяется спецификацией Compose . Этот формат объединяет версии 2.x и 3.x и реализован в Compose 1.27.0+ .

v2 и v3 Декларация

Примечание : При указании Compose версии файла для использования, убедитесь , чтобы указать обе главные и второстепенные номера. Если дополнительная версия не указана, по умолчанию используется 0 , а не последняя дополнительная версия.

Матрица совместимости показывает сочинить версии файлов , отображенные в выпусках Docker Engine.

Чтобы перенести проект на более позднюю версию, см. раздел « Обновление ».

Примечание . Если вы используете несколько файлов Compose или сервисов расширения , каждый файл должен иметь одну и ту же версию — например, вы не можете смешивать версии 1 и 2 в одном проекте.

Некоторые вещи различаются в зависимости от того,какую версию вы используете:

  • Структура и разрешенные ключи конфигурации
  • Минимальная версия Docker Engine,которую вы должны запустить.
  • Поведение Compose в отношении сетевого взаимодействия

Эти различия объясняются ниже.

Версия 1 (устаревшая)

Файлы компоновки, в которых не указана версия, считаются «версией 1». В этих файлах все службы объявлены в корне документа.

Версия 1 поддерживается Compose до 1.6.x . Это будет устаревшим в будущем выпуске Compose.

Файлы версии 1 не могут объявлять именованные тома , сети или аргументы сборки .

Compose не использует преимущества сети при использовании версии 1: каждый контейнер помещается в bridge сеть по умолчанию и доступен из любого другого контейнера по его IP-адресу. Вам нужно использовать links , чтобы включить обнаружение между контейнерами.

Version 2

Создание файлов с использованием синтаксиса версии 2 должно указывать номер версии в корне документа. Все сервисы должны быть объявлены в ключе services .

Файлы версии 2 поддерживаются Compose 1.6.0+ и требуют Docker Engine версии 1.10.0+ .

Именованные тома могут быть объявлены в ключе Volumes, а volumes могут быть объявлены в ключе Networks networks

По умолчанию каждый контейнер присоединяется к сети по умолчанию для всего приложения и доступен для обнаружения по имени хоста, совпадающему с именем службы. Это означает , что ссылки в значительной степени не нужны. Дополнительные сведения см . в разделе Сеть в Compose .

Note

При указании используемой версии файла Compose обязательно укажите как старший, так и второстепенный номера . Если дополнительная версия не указана, по умолчанию используется 0 , а не последняя дополнительная версия. В результате функции, добавленные в более поздних версиях, не будут поддерживаться. Например:

Более подробный пример,определяющий объемы и сети:

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

Параметр depends_on может использоваться вместо ссылок для указания зависимостей между службами и порядком запуска.

Подстановка переменных также была добавлена ​​в версии 2.

Version 2.1

Обновление версии 2, которое вводит новые параметры, доступные только в Docker Engine версии 1.12.0+ . Файлы версии 2.1 поддерживаются Compose 1.9.0+ .

Вводит следующие дополнительные параметры:

Version 2.2

Обновление версии 2.1 , в котором представлены новые параметры, доступные только в Docker Engine версии 1.13.0+ . Файлы версии 2.2 поддерживаются Compose 1.13.0+ . Эта версия также позволяет указать значения шкалы по умолчанию в конфигурации службы.

Вводит следующие дополнительные параметры:

Version 2.3

Обновление версии 2.2, которое вводит новые параметры, доступные только в Docker Engine версии 17.06.0+ . Файлы версии 2.3 поддерживаются Compose 1.16.0+ .

Вводит следующие дополнительные параметры:

  • target , extra_hosts и shm_size для конфигураций сборки
  • start_period для healthchecks
  • runtime для определений службы

Version 2.4

Обновление версии 2.3, которое вводит новые параметры, доступные только в Docker Engine версии 17.12.0+ . Файлы версии 2.4 поддерживаются Compose 1.21.0+ .

Вводит следующие дополнительные параметры:

  • platform для определения услуг
  • Поддержка полей расширения в корне определения службы,сети и тома

Version 3

Версия 3, предназначенная для перекрестной совместимости между Compose и режимом роя Docker Engine , удаляет несколько параметров и добавляет еще несколько.

Удалены: volume_driver , volumes_from , cpu_shares , cpu_quota , cpuset , mem_limit , memswap_limit , extends , group_add . См. руководство по обновлению , чтобы узнать, как перейти от них. (Дополнительную информацию о extends см . в разделе Расширение служб .)

Примечание : При указании Compose версии файла для использования, убедитесь , чтобы указать обе главные и второстепенные номера. Если дополнительная версия не указана, по умолчанию используется 0 , а не последняя дополнительная версия. В результате функции, добавленные в более поздних версиях, не будут поддерживаться. Например:

Version 3.1

Обновление версии 3 , в котором представлены новые параметры, доступные только в Docker Engine версии 1.13.1+ и выше.

Вводит следующие дополнительные параметры:

Version 3.2

Обновление версии 3 , в котором представлены новые параметры, доступные только в Docker Engine версии 17.04.0+ и выше.

Вводит следующие дополнительные параметры:

  • cache_from в конфигурациях сборки
  • Длинный синтаксис для портов и монтирования томов
  • attachable сетевой драйвер

Version 3.3

Обновление версии 3, которое вводит новые параметры, доступные только в Docker Engine версии 17.06.0+ и выше.

Вводит следующие дополнительные параметры:

Version 3.4

Обновление версии 3, которое вводит новые параметры. Он доступен только с версией Docker Engine 17.09.0 и выше.

Вводит следующие дополнительные параметры:

  • target и network в конфигурациях сборки
  • start_period для healthchecks
  • order на обновление конфигураций
  • name для томов

Version 3.5

Обновление версии 3, которое вводит новые параметры. Он доступен только с версией Docker Engine 17.12.0 и выше.

Вводит следующие дополнительные параметры:

  • isolation в определениях службы
  • name для сетей, секретов и конфигов
  • shm_size в конфигурациях сборки

Version 3.6

Обновление версии 3, которое вводит новые параметры. Он доступен только с версией Docker Engine 18.02.0 и выше.

Вводит следующие дополнительные параметры:

  • размер tmpfs длямонтирования типа tmpfs

Version 3.7

Обновление версии 3, которое вводит новые параметры. Он доступен только с версией Docker Engine 18.06.0 и выше.

Name already in use

docs / compose / compose-file / compose-versioning.md

  • Go to file T
  • Go to line L
  • Copy path
  • Copy permalink
  • Open with Desktop
  • View raw
  • Copy raw contents Copy raw contents

Copy raw contents

Copy raw contents

The Compose file is a YAML file defining services, networks, and volumes for a Docker application.

The Compose file formats are now described in these references, specific to each version.

Reference file What changed in this version
Compose Specification (most current, and recommended) Versioning
Version 3 Version 3 updates
Version 2 Version 2 updates
Version 1 (Deprecated) Version 1 updates

The topics below explain the differences among the versions, Docker Engine compatibility, and how to upgrade.

There are several versions of the Compose file format – 1, 2, 2.x, and 3.x

Looking for more detail on Docker and Compose compatibility?

We recommend keeping up-to-date with newer releases as much as possible. However, if you are using an older version of Docker and want to determine which Compose release is compatible, refer to the Compose release notes. Each set of release notes gives details on which versions of Docker Engine are supported, along with compatible Compose file format versions. (See also, the discussion in [issue #3404](<< site.repo >>/issues/3404).)

For details on versions and how to upgrade, see Versioning and Upgrading.

There are three legacy versions of the Compose file format:

Version 1. This is specified by omitting a version key at the root of the YAML.

Version 2.x. This is specified with a version: ‘2’ or version: ‘2.1’ , etc., entry at the root of the YAML.

Version 3.x, designed to be cross-compatible between Compose and the Docker Engine’s swarm mode. This is specified with a version: ‘3’ or version: ‘3.1’ , etc., entry at the root of the YAML.

The latest and recommended version of the Compose file format is defined by the Compose Specification. This format merges the 2.x and 3.x versions and is implemented by Compose 1.27.0+.

v2 and v3 Declaration

Note : When specifying the Compose file version to use, make sure to specify both the major and minor numbers. If no minor version is given, 0 is used by default and not the latest minor version.

The Compatibility Matrix shows Compose file versions mapped to Docker Engine releases.

To move your project to a later version, see the Upgrading section.

Note : If you’re using multiple Compose files or extending services, each file must be of the same version — you cannot, for example, mix version 1 and 2 in a single project.

Several things differ depending on which version you use:

  • The structure and permitted configuration keys
  • The minimum Docker Engine version you must be running
  • Compose’s behaviour with regards to networking

These differences are explained below.

Version 1 (Deprecated)

Compose files that do not declare a version are considered «version 1». In those files, all the services are declared at the root of the document.

Version 1 is supported by Compose up to 1.6.x. It will be deprecated in a future Compose release.

Version 1 files cannot declare named volumes, networks or build arguments.

Compose does not take advantage of networking when you use version 1: every container is placed on the default bridge network and is reachable from every other container at its IP address. You need to use links to enable discovery between containers.

Compose files using the version 2 syntax must indicate the version number at the root of the document. All services must be declared under the services key.

Version 2 files are supported by Compose 1.6.0+ and require a Docker Engine of version 1.10.0+.

Named volumes can be declared under the volumes key, and networks can be declared under the networks key.

By default, every container joins an application-wide default network, and is discoverable at a hostname that’s the same as the service name. This means links are largely unnecessary. For more details, see Networking in Compose.

Note

When specifying the Compose file version to use, make sure to specify both the major and minor numbers. If no minor version is given, 0 is used by default and not the latest minor version. As a result, features added in later versions will not be supported. For example:

is equivalent to:

A more extended example, defining volumes and networks:

Several other options were added to support networking, such as:

The depends_on option can be used in place of links to indicate dependencies between services and startup order.

Variable substitution also was added in Version 2.

An upgrade of version 2 that introduces new parameters only available with Docker Engine version 1.12.0+. Version 2.1 files are supported by Compose 1.9.0+.

Introduces the following additional parameters:

An upgrade of version 2.1 that introduces new parameters only available with Docker Engine version 1.13.0+. Version 2.2 files are supported by Compose 1.13.0+. This version also allows you to specify default scale numbers inside the service’s configuration.

Introduces the following additional parameters:

An upgrade of version 2.2 that introduces new parameters only available with Docker Engine version 17.06.0+. Version 2.3 files are supported by Compose 1.16.0+.

Introduces the following additional parameters:

    , extra_hosts and shm_size for build configurations
  • start_period for healthchecks for service definitions

An upgrade of version 2.3 that introduces new parameters only available with Docker Engine version 17.12.0+. Version 2.4 files are supported by Compose 1.21.0+.

Introduces the following additional parameters:

    for service definitions
  • Support for extension fields at the root of service, network, and volume definitions

Designed to be cross-compatible between Compose and the Docker Engine’s swarm mode, version 3 removes several options and adds several more.

Removed: volume_driver , volumes_from , cpu_shares , cpu_quota , cpuset , mem_limit , memswap_limit , extends , group_add . See the upgrading guide for how to migrate away from these. (For more information on extends , see Extending services.)

Note : When specifying the Compose file version to use, make sure to specify both the major and minor numbers. If no minor version is given, 0 is used by default and not the latest minor version. As a result, features added in later versions will not be supported. For example:

is equivalent to:

An upgrade of version 3 that introduces new parameters only available with Docker Engine version 1.13.1+, and higher.

Introduces the following additional parameters:

An upgrade of version 3 that introduces new parameters only available with Docker Engine version 17.04.0+, and higher.

Introduces the following additional parameters:

    in build configurations
  • Long syntax for ports and volume mounts network driver option

An upgrade of version 3 that introduces new parameters only available with Docker Engine version 17.06.0+, and higher.

Introduces the following additional parameters:

An upgrade of version 3 that introduces new parameters. It is only available with Docker Engine version 17.09.0 and higher.

Introduces the following additional parameters:

    and network in build configurations
  • start_period for healthchecks
  • order for update configurations
  • name for volumes

An upgrade of version 3 that introduces new parameters. It is only available with Docker Engine version 17.12.0 and higher.

Introduces the following additional parameters:

    in service definitions
  • name for networks, secrets and configs
  • shm_size in build configurations

An upgrade of version 3 that introduces new parameters. It is only available with Docker Engine version 18.02.0 and higher.

Introduces the following additional parameters:

    for tmpfs -type mounts

An upgrade of version 3 that introduces new parameters. It is only available with Docker Engine version 18.06.0 and higher.

Introduces the following additional parameters:

    in service definitions in deploy configurations
  • Support for extension fields at the root of service, network, volume, secret and config definitions

An upgrade of version 3 that introduces new parameters. It is only available with Docker Engine version 19.03.0 and higher.

Introduces the following additional parameters:

    in placement configurations
  • template_driver option for config and secret configurations. This option is only supported when deploying swarm services using docker stack deploy .
  • driver and driver_opts option for secret configurations. This option is only supported when deploying swarm services using docker stack deploy .

Version 2.x to 3.x

Between versions 2.x and 3.x, the structure of the Compose file is the same, but several options have been removed:

volume_driver : Instead of setting the volume driver on the service, define a volume using the top-level volumes option and specify the driver there.

volumes_from : To share a volume between services, define it using the top-level volumes option and reference it from each service that shares it using the service-level volumes option.

cpu_shares , cpu_quota , cpuset , mem_limit , memswap_limit : These have been replaced by the resources key under deploy . deploy configuration only takes effect when using docker stack deploy , and is ignored by docker-compose .

extends : This option has been removed for version: «3.x» Compose files. (For more information, see Extending services.)

group_add : This option has been removed for version: «3.x» Compose files.

pids_limit : This option has not been introduced in version: «3.x» Compose files.

link_local_ips in networks : This option has not been introduced in version: «3.x» Compose files.

Version 1 to 2.x

In the majority of cases, moving from version 1 to 2 is a very simple process:

  1. Indent the whole file by one level and put a services: key at the top.
  2. Add a version: ‘2’ line at the top of the file.

It’s more complicated if you’re using particular configuration features:

dockerfile : This now lives under the build key:

log_driver , log_opt : These now live under the logging key:

links with environment variables: environment variables created by links, such as CONTAINERNAME_PORT , ` have been deprecated for some time. In the new Docker network system, they have been removed. You should either connect directly to the appropriate hostname or set the relevant environment variable yourself, using the link hostname:

external_links : Compose uses Docker networks when running version 2 projects, so links behave slightly differently. In particular, two containers must be connected to at least one network in common in order to communicate, even if explicitly linked together.

Either connect the external container to your app’s default network, or connect both the external container and your service’s containers to an external network.

net : This is now replaced by network_mode:

If you’re using net: «container:[service name]» , you must now use network_mode: «service:[service name]» instead.

If you’re using net: «container:[container name/id]» , the value does not need to change.

volumes with named volumes: these must now be explicitly declared in a top-level volumes section of your Compose file. If a service mounts a named volume called data , you must declare a data volume in your top-level volumes section. The whole file might look like this:

By default, Compose creates a volume whose name is prefixed with your project name. If you want it to just be called data , declare it as external:

docker-compose 1.20.0 introduces a new —compatibility flag designed to help developers transition to version 3 more easily. When enabled, docker-compose reads the deploy section of each service’s definition and attempts to translate it into the equivalent version 2 parameter. Currently, the following deploy keys are translated:

    limits and memory reservations condition and max_attempts

All other keys are ignored and produce a warning if present. You can review the configuration that will be used to deploy by using the —compatibility flag with the config command.

Do not use this in production!

We recommend against using —compatibility mode in production. Because the resulting configuration is only an approximate using non-Swarm mode properties, it may produce unexpected results.

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

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