The post has been translated automatically. Original language: Russian
Docker Compose 5.8.1 was released on November 27. This is a corrective release of the 5.8 branch, but for those who run Compose in CI and on booths, it is more important than you might think by the number. There are eight fixes in it. The most noticeable ones change the behavior of waiting for services to be ready, pre_stop hooks, and project selection in CLI teams.
Waiting for readiness now takes into account all replicas
Previously, docker compose up --wait and depends_on dependency with the service_completed_successfully condition considered the scaled service ready as soon as one replica met the condition. If the service had three instances, the wait could end when two of them were still running.
Since version 5.8.1, a service is considered healthy only when all its replicas are ready. The service_completed_successfully condition is met only when all replicas have terminated with code 0. If at least one replica has dropped, the wait also fails. The exited, unhealthy, and unknown health status statuses still interrupt the wait immediately.
The pre_stop hooks are triggered every time you stop
pre_stop hooks are needed for a neat completion: reset buffers, remove node from balancing, close connections. In this issue, their behavior has been corrected in three places at once.:
- hooks are executed before the plan stops the container.;
- previously, the hook did not run when up recreated the container after changing its configuration. Hooks are now triggered at any stop: when recreating, reducing the number of replicas, recreating a network or volume, and stopping dependent services.;
- if the pre_stop hook fails to start, the container stops or restarts anyway and does not hang in an intermediate state.
According to the description of the change, when recreating, hooks are now triggered before a replacement is created. If the hook fails, the up command also fails, and the old container continues to work.
One rule for choosing a project
Previously, different parts of the CLI defined the project name in different order. If the COMPOSE_PROJECT_NAME variable was set, the file upload error was silently swallowed, and the stop, down, and ps commands restored the project using container labels. Now the order is the same: first the --project-name flag, then the COMPOSE_PROJECT_NAME variable, then the name from the file itself.
If the file explicitly specified via --file or COMPOSE_FILE is not readable, this is now a serious error. If a file found automatically turns out to be broken, Compose issues a warning and works by tagging. The restart and wait commands with a non-existent service name now report an error, rather than silently terminating.
Other changes
- If possible, OCI artifacts are loaded directly from the cache.;
- watch removes a large number of synchronized paths in multiple exec calls, rather than one.;
- The model described in the short form is no longer downloaded again.;
- if the engine does not have HTTP/2, Compose assumes that it does not support jobs.;
- updated dependencies, including the Docker CLI to 29.10.1.
What does this mean in practice?
The main risk of the upgrade is that pipelines that were previously "green" may start to fall. If CI has an up --wait on a service with multiple replicas and one of them is unstable, it used to go unnoticed, but now the step will drop. This is the correct behavior, but it's worth running the pipeline on the test branch in advance. The wait may also get longer: now Compose is waiting for the slowest replica.
The second point concerns the deployment scripts. Check if there are any calls with a non-existent COMPOSE_FILE or a typo in the service name for restart: previously, such errors were silent, now the command will end with a non-zero code. If the pre_stop hooks do something heavy, keep in mind that they are now executed every time the container is recreated, and a hook error will stop up. Hooks should be made idempotent and fast.
The draft text was prepared with the participation of AI, the facts were checked against the original source — official release notes Docker Compose 5.8.1 and descriptions of changes in the project repository on GitHub
27 ноября вышел Docker Compose 5.8.1. Это корректирующий выпуск ветки 5.8, но для тех, кто запускает Compose в CI и на стендах, он важнее, чем можно подумать по номеру. В нём восемь исправлений. Самые заметные меняют поведение ожидания готовности сервисов, хуков pre_stop и выбора проекта в командах CLI.
Ожидание готовности теперь учитывает все реплики
Раньше docker compose up --wait и зависимость depends_on с условием service_completed_successfully считали масштабированный сервис готовым, как только условию отвечала одна реплика. Если у сервиса было три экземпляра, ожидание могло закончиться, когда два из них ещё стартовали.
С версии 5.8.1 сервис считается здоровым, только когда готовы все его реплики. Условие service_completed_successfully выполняется, только когда все реплики завершились с кодом 0. Если упала хотя бы одна реплика, ожидание тоже завершается ошибкой. Статусы exited, unhealthy и неизвестный статус здоровья по-прежнему прерывают ожидание сразу.
Хуки pre_stop срабатывают при каждой остановке
Хуки pre_stop нужны для аккуратного завершения: сбросить буферы, снять узел с балансировки, закрыть соединения. В этом выпуске их поведение исправили сразу в трёх местах:
- хуки выполняются до того, как план остановит контейнер;
- раньше хук не запускался, когда up пересоздавал контейнер после изменения его конфигурации. Теперь хуки срабатывают при любой остановке: при пересоздании, уменьшении числа реплик, пересоздании сети или тома и остановке зависимых сервисов;
- если хук pre_stop не удаётся запустить, контейнер всё равно останавливается или перезапускается и не зависает в промежуточном состоянии.
По описанию изменения, при пересоздании хуки теперь запускаются до того, как создаётся замена. Если хук завершился ошибкой, команда up тоже завершается ошибкой, а старый контейнер продолжает работать.
Одно правило выбора проекта
Раньше разные части CLI определяли имя проекта в разном порядке. Если была задана переменная COMPOSE_PROJECT_NAME, ошибка загрузки файла молча проглатывалась, и команды stop, down и ps восстанавливали проект по меткам контейнеров. Теперь порядок один: сначала флаг --project-name, затем переменная COMPOSE_PROJECT_NAME, затем имя из самого файла.
Если явно указанный через --file или COMPOSE_FILE файл не читается, это теперь жёсткая ошибка. Если битым оказался файл, найденный автоматически, Compose выдаёт предупреждение и работает по меткам. Команды restart и wait с несуществующим именем сервиса теперь сообщают об ошибке, а не завершаются молча.
Прочие изменения
- загрузка OCI-артефактов по возможности идёт напрямую из кеша;
- watch удаляет большое число синхронизированных путей в несколько вызовов exec, а не одним;
- модель, описанная в короткой форме, больше не скачивается повторно;
- если у движка нет HTTP/2, Compose считает, что он не поддерживает jobs;
- обновлены зависимости, в том числе Docker CLI до 29.10.1.
Что это значит на практике
Главный риск обновления в том, что пайплайны, которые раньше «зеленели», могут начать падать. Если в CI стоит up --wait на сервисе с несколькими репликами и одна из них нестабильна, раньше это проходило незаметно, а теперь шаг упадёт. Это правильное поведение, но стоит заранее прогнать пайплайн на тестовой ветке. Ожидание тоже может стать дольше: теперь Compose ждёт самую медленную реплику.
Второй момент касается скриптов деплоя. Проверьте, нет ли в них вызовов с несуществующим COMPOSE_FILE или опечаткой в имени сервиса для restart: раньше такие ошибки проходили тихо, теперь команда завершится с ненулевым кодом. Если хуки pre_stop делают что-то тяжёлое, учтите, что теперь они выполняются и при каждом пересоздании контейнера, а ошибка хука остановит up. Хуки стоит сделать идемпотентными и быстрыми.
Черновик текста подготовлен с участием ИИ, факты сверены с первоисточником — официальные release notes Docker Compose 5.8.1 и описания изменений в репозитории проекта на GitHub
Comments 0
Newest Popular