首先,docker compose有一个关键字depends_on是可以一定程度解决services之间的依赖问题,但是depends_on仅仅只是指定了services的启动顺序,并不能保证,前置service完全启动后,后置service才启动。

此时,需要另一个关键字叫healthcheck

样例

nacos版本为v2.3.0

  mysql_nacos:
    container_name: mysql_nacos
    build:
      context: .
      dockerfile: ./image/mysql/5.7/Dockerfile
    image: example/mysql:5.7
    env_file:
      - ../env/mysql.env
    volumes:
      - ./mysql:/var/lib/mysql
#    ports:
#      - "3307:3306"
    healthcheck:
      test: [ "CMD", "mysqladmin" ,"ping", "-h", "localhost", "-u", "root", "-p${MYSQL_ROOT_PASSWORD}" ]
      interval: 10s
      timeout: 10s
      retries: 10
        
  nacos1:
    hostname: nacos1
    container_name: nacos1
    image: nacos/nacos-server:${NACOS_VERSION}
    volumes:
      - ./cluster-logs/nacos1:/home/nacos/logs
#    ports:
#      - "7848:7848"
#      - "8845:8848"
#      - "9868:9848"
#      - "9850:9849"
    env_file:
      - ../env/nacos-hostname.env
#    restart: always
    healthcheck:
      test: [ "CMD", "curl", "-f", "http://localhost:8848/nacos/v1/console/health/readiness" ]
      interval: 10s
      timeout: 10s
      retries: 10
    depends_on:
      mysql_nacos:
        condition: service_healthy
        
  nginx_nacos:
    hostname: nginx_nacos
    image: nginx:stable
    container_name: nginx_nacos
    volumes:
      - ../nginx_nacos/nginx.conf:/etc/nginx/nginx.conf
      - ../nginx_nacos/conf.d/default.conf:/etc/nginx/conf.d/default.conf
      - ../nginx_nacos/logs:/var/log/nginx
      - ../nginx_nacos/html:/usr/share/nginx/html
    ports:
      - "80:80"
    depends_on:
      nacos1:
        condition: service_healthy

这是一个双层依赖,nginx_nacos依赖于nacos1,同时nacos1依赖于mysql_nacos

mysql_nacos基于 healthcheck:test: [ "CMD", "mysqladmin" ,"ping", "-h", "localhost", "-u", "root", "-p${MYSQL_ROOT_PASSWORD}" ]来确认自己的健康状态,只有当test内容执行成功并返回状态码0,才会认为此service已完全执行成功。

同理nacos服务是基于healthcheck:test: [ "CMD", "curl", "-f", "http://localhost:8848/nacos/v1/console/health/readiness" ]来判断健康状态的。

GitHub 加速计划 / compose / compose
33.27 K
5.15 K
下载
compose - Docker Compose是一个用于定义和运行多容器Docker应用程序的工具,通过Compose文件格式简化应用部署过程。
最近提交(Master分支:2 个月前 )
501b5acd Add `jhrotko` to Core Maintainers. Signed-off-by: Laura Brehm <laurabrehm@hey.com> 5 天前
f51bc4cd Signed-off-by: Guillaume Lours <705411+glours@users.noreply.github.com> 5 天前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐