I am deploying a few different docker containers, mysql being the first one. I want to run scripts as soon as database is up and proceed to building other containers. The script has been failing because it was trying to run when the entrypoint script, which sets up mysql (from this official mysql container), was still running.
sudo docker run --name mysql -e MYSQL_ROOT_PASSWORD=MY_ROOT_PASS -p 3306:3306 -d mysql
[..] wait for mysql to be ready [..]
mysql -h 127.0.0.1 -P 3306 -u root --password=MY_ROOT_PASS < MY_SQL_SCRIPT.sql
Is there a way to wait for a signal of an entrypoiny mysql setup script finishing inside the docker container? Bash sleep seems like a suboptimal solution.
EDIT: Went for a bash script like this. Not the most elegant and kinda brute force but works like a charm. Maybe someone will find that useful.
OUTPUT="Can't connect"
while [[ $OUTPUT == *"Can't connect"* ]]
do
OUTPUT=$(mysql -h $APP_IP -P :$APP_PORT -u yyy --password=xxx < ./my_script.sql 2>&1)
done
This was more or less mentioned in comments to other answers, but I think it deserves it's own entry.
First of all you can run your container in the following manner:
There is also an equivalent in the Dockerfile.
With that command your
docker ps
anddocker inspect
will show you health status of your container. For mysql in particular this method has the advantage ofmysqladmin
being available inside the container, so you do not need to install it on the docker host.Then you can simply loop in a bash script to wait on the status to become healthy. The following bash script is created by Dennis.
Now you can do this in your script:
and your script will wait until the container is up and running. The script will exit if the container becomes unhealthy, which is possible, if for example docker host is out of memory, so that the mysql cannot allocate enough of it for itself.
On your
ENTRYPOINT
script, you have to check if you have a valid MySQL connection or not.So in this solution, I will show you how to run a PHP script to check if a MySQL Container is able to take connection. If you want to know why I think this is a better approach check my comment here.
File
entrypoint.sh
By running this, you are essentially blocking any bootstrapping logic of your container UNTIL you have a valid MySQL Connection.
This little bash loop waits for mysql to be open, shouldn't require any extra packages to be installed:
The following health-check works for all my mysql containers:
https://github.com/docker-library/mysql/blob/master/5.7/docker-entrypoint.sh docker-entrypoint.sh doesn't support merging customized .sql yet.
I think you can modify docker-entrypoint.sh to merge your sql so it can be executed once mysql instance is ready.