Docker-compose 检查 mysql 连接是否准备就绪
我正在尝试确保我的应用程序容器在数据库容器启动并准备接受连接之前不会运行迁移/启动.
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 文件 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",测试 -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 容器健康(基本上在 mysqladmin 启动并接受连接之前),api 容器才会启动.
The api container will not start until the db container is healthy (basically until mysqladmin is up and accepting connections.)
相关文章