在docker-compose.yml中配置了多个service,在docker-compose up

后各个容器的启动并无依赖关系,如果需要控制容器的启动顺序需要使用到depends_no 属性,例如:

version: "3.9"
services:
  web:
    build: .
    depends_on:
      - db
      - redis
  redis:
    image: redis
  db:
    image: postgres

上面例子中的db,redis会先于web启动,当docker-compose down 的时候,web会先于db, redis删除。

depends_on只保证db, redis先于web启动,但有可能出现web先于db启动完成而无法连接数据库的情况,这种情况需用使用condition属性进行探活,看下面例子:

services:
  web:
    build: .
    depends_on:
      db:
        condition: service_healthy
        restart: true
      redis:
        condition: service_started
  redis:
    image: redis
  db:
    image: postgres
		healthcheck:
      test: ["CMD-SHELL","pg_isready","-d","localhost"]
      timeout: 10s
      retries: 5

通过对PostgresSQL进行5次探活,每次10s,探活成功后启动web,否则放弃。

condition有3个选项:

  • service_started 这个和没有condition的效果一样
  • service_healthy 依赖容器探活成功后再启动容器
  • service_completed_successfully 依赖容器启动成功并退出后再启动容器

参考:

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

https://docs.docker.com/compose/startup-order/