docker-撰写健康检查通过,仍然不健康

docker-compose health check passed, still unhealthy

condition was removed compose spec in versions 3.0 to 3.8 but is now back! Using version of the compose spec v3.9, you can use condition as an option in long syntax form of depends_on.

我使用 docker compose 启动 MySQL 和 Java Web 项目, JavaWeb的启动需要依赖MySQL来创建完整的数据,所以我使用healthcheck

但是mysql的 healthcheck有问题,这是我的docker-compose

# docker-compose.yml
version: "3.9"  

services:

  mysql:
    build:
      context: ./mysql
    command: [
        'mysqld',
        '--character-set-server=utf8mb4',
        '--collation-server=utf8mb4_unicode_ci',
        '--default-time-zone=+8:00',
        '--lower-case-table-names=1'
    ]
    ports:
      - "3306:3306"
    environment:
      MYSQL_DATABASE: fuba-db
      MYSQL_ROOT_PASSWORD: fb123456
    healthcheck:
      test: "mysql -uroot -p$$MYSQL_ROOT_PASSWORD  -e 'SELECT * FROM factor_header' fuba-db "
      interval: 1s
      timeout: 3s
      retries: 3

  redis:
    build:
      ......

  nginx:
    build:
      ......

  fubaquant:
    build:
      context: ./webapps
    ports:
      - "8080:8080"
    volumes:
      - /mnt/java/jar:/home/ruoyi  #jar包
    depends_on:
      mysql:
        condition: service_healthy
      redis:
        condition: service_started

错误的语句是:

test: "mysql -uroot -p$$MYSQL_ROOT_PASSWORD  -e 'SELECT * FROM factor_header' fuba-db "

控制台输出:

pro-mysql-1      | 2022-04-07T08:16:54.203710Z 1 [Warning] root@localhost is created with an empty password ! Please consider switching off the --initialize-insecure option.
container for service "mysql" is unhealthy

由于fubaquant depends_on mysql healthcheck,fubaquant也没有启动

mysql容器的健康检查日志为:

我检查了 mysql 的健康检查日志,它也很健康

感谢您的帮助

您似乎正在尝试 运行 使用错误的用户名和密码进行健康检查。你有

healthcheck:
      test: ["CMD", "mysqladmin", "-u$mysql", "-p3456",  "ping", "-h", "localhost"]

$mysql3456 将尝试解析那些变量的值。您想要的是改用以下内容。

healthcheck:
      test: ["CMD", "mysqladmin", "-u$MYSQL_USER", "-p$MYSQL_PASSWORD",  "ping", "-h", "localhost"]

这将尝试 运行 mysaqladmin 使用用户 mysql 和密码 123456(都定义为 mysql 服务的环境变量docker-compose)

我将运行状况检查配置为仅允许重试 3 次,间隔为 1 秒。当 compose 正在启动 java 时,mysql 服务在这 3 秒延迟内未达到健康状态,因此 compose 停止并报告此错误。 增加重试次数后就可以了