Docker-compose 检查 mysql 连接是否准备好

Docker-compose check if mysql connection is ready(Docker-compose 检查 mysql 连接是否准备好)
本文介绍了Docker-compose 检查 mysql 连接是否准备好的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试确保我的应用容器在 db 容器启动并准备好接受连接之前不会运行迁移/启动.

I am trying to make sure that my app container does not run migrations / start until the db container is started and READY TO accept connections.

所以我决定使用运行状况检查并依赖于 docker compose file v2 中的选项.

So I decided to use the healthcheck and depends on option in docker compose file v2.

在应用程序中,我有以下内容

In the app, I have the following

app:
    ...
    depends_on:
      db:
      condition: service_healthy

另一方面,数据库具有以下运行状况检查

The db on the other hand has the following healthcheck

db:
  ...
  healthcheck:
    test: TEST_GOES_HERE
    timeout: 20s
    retries: 10

我尝试了几种方法,例如:

I have tried a couple of approaches like :

  1. 确保已创建 db DIR<代码>测试:[CMD",test -f var/lib/mysql/db"]
  2. 获取mysql版本:<代码>测试:["CMD", "echo 'SELECT version();'| mysql"]
  3. Ping 管理员(将 db 容器标记为健康但似乎不是有效的测试)<代码>测试:[CMD"、mysqladmin"、ping"、-h"、localhost"]

有没有人可以解决这个问题?

Does anyone have a solution to this?

推荐答案

version: "2.1"
services:
    api:
        build: .
        container_name: api
        ports:
            - "8080:8080"
        depends_on:
            db:
                condition: service_healthy
    db:
        container_name: db
        image: mysql
        ports:
            - "3306"
        environment:
            MYSQL_ALLOW_EMPTY_PASSWORD: "yes"
            MYSQL_USER: "user"
            MYSQL_PASSWORD: "password"
            MYSQL_DATABASE: "database"
        healthcheck:
            test: ["CMD", "mysqladmin" ,"ping", "-h", "localhost"]
            timeout: 20s
            retries: 10

在 db 容器健康之前,api 容器不会启动(基本上直到 mysqladmin 启动并接受连接.)

The api container will not start until the db container is healthy (basically until mysqladmin is up and accepting connections.)

这篇关于Docker-compose 检查 mysql 连接是否准备好的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Hibernate reactive No Vert.x context active in aws rds(AWS RDS中的休眠反应性非Vert.x上下文处于活动状态)
Bulk insert with mysql2 and NodeJs throws 500(使用mysql2和NodeJS的大容量插入抛出500)
Flask + PyMySQL giving error no attribute #39;settimeout#39;(FlASK+PyMySQL给出错误,没有属性#39;setTimeout#39;)
auto_increment column for a group of rows?(一组行的AUTO_INCREMENT列?)
Sort by ID DESC(按ID代码排序)
SQL/MySQL: split a quantity value into multiple rows by date(SQL/MySQL:按日期将数量值拆分为多行)