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 :
- 确保已创建 db DIR<代码>测试:[CMD",test -f var/lib/mysql/db"]
- 获取mysql版本:<代码>测试:["CMD", "echo 'SELECT version();'| mysql"]
- 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.)
相关文章