使用docker-compose确保mysql可以正常启动

问题

在compose文件中配置了depend_on,里面有db,但是web容器内在启动时报连接不到mysql 3306的错误

分析

容器虽然起来了,但是mysql没有启动,导致无法访问mysql数据库

解决方案

在mysql的service中,增加healthcheck节点,测试mysql数据库是否可以连接;
在依赖mysql的servcie中,配置depend_on,并注意添加condition: service_healthy

version: '2.1'
services:
  web:
    build:
      context: .
      dockerfile: Dockerfile
    command: bash -c "/usr/bin/true"  # I run tests from here
    container_name: foo_web
    depends_on:
      db:
        condition: service_healthy  # 对应的servcie里面需要配置 healthcheck
  db:
    image: mariadb:latest
    container_name: foo_db
    restart: always
    healthcheck:
      test: "/usr/bin/mysql --user={登录用户名} --password={登录密码} --execute \"SHOW DATABASES;\""
      interval: 3s # 间隔时间
      timeout: 1s  # 超时时间
      retries: 5   # 重试次数
    environment:
      MYSQL_DATABASE: {库名称}
      MYSQL_USER: {登录用户名}
      MYSQL_PASSWORD: {登录密码}
posted @ 2022-07-15 17:21  远方V3  阅读(738)  评论(0编辑  收藏  举报