我们知道启动数据库有时需要时间,所以如果你想在发出任何查询之前知道它是否已经启动,你可以使用下面的例子。
docker-compose.yml
version: '3'
services:
mysql:
build:
context: ./docker/mysql
...
volumes:
- ./docker/mysql/init.sh:/docker-entrypoint-initdb.d/init.sh
Docker文件
FROM mysql:5.7.22
COPY init.sh /docker-entrypoint-initdb.d/init.sh
init.sh
#!/bin/bash
echo "Checking if the database is up ..."
while ! mysqladmin ping -h"localhost" --silent; do
echo "Waiting for the database to come up ..."
sleep 2
done
echo "Database is up ..."
# Run an example query
mysql -u root -proot -e "USE mysql;"
测试
$ docker-compose up -d
...
mysql_1 | Checking if the database is up ...
mysql_1 | Waiting for the database to come up ...
mysql_1 | Waiting for the database to come up ...
mysql_1 | Database is up ...
...