We know that bringing the database up sometimes takes time so if you want to know if it is up before issuing any queries, you can use example below.


docker-compose.yml


version: '3'

services:

mysql:
build:
context: ./docker/mysql
...
volumes:
- ./docker/mysql/init.sh:/docker-entrypoint-initdb.d/init.sh

Dockerfile


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;"

Test


$ 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 ...
...