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