Docker Compose怎么保证其他服务在Nacos完全启动后再启动

2023-12-13 05:51:46

首先,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" ]来判断健康状态的。

文章来源:https://blog.csdn.net/m0_51390969/article/details/134946287
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。