Docker Compose 等待服务可用后再启动另一个服务

喜大普奔!

Docker Compose 终于支持了等待一个服务可用后再启动另一个服务的功能。

老版本的 docker compose 在服务之间使用 depends_on 指定依赖关系后,其只能保证容器按照顺序启动。

但是一些服务启动是需要时间的,比如数据库,仅仅按顺序启动容器,无法保证其它容器在访问数据库时其已经可用了。

在之前只能使用 wait-for-it.sh 或 dockerize 之类的脚本来等待依赖服务可用。

在 docker compose 版本 1.27.0 支持了在 depends_on 中指定 condntion 的功能,配合 healthcheck 功能,就可用实现等待依赖服务器可用再启动的效果了。

version: '3.8'

services:
  db:
    image: postgres:15
    environment:
      - POSTGRES_USER=user
      - POSTGRES_PASSWORD=password
      - POSTGRES_DB=mydb
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U postgres"]
      interval: 10s
      timeout: 5s
      retries: 5

  web:
    image: my-web-app:latest
    depends_on:
      db:
        condition: service_healthy
    ports:
      - "80:8000"

https://docs.docker.com/reference/compose-file/services/#depends_on

https://docs.docker.com/reference/compose-file/services/#healthcheck

comments powered by Disqus