Mysql – way to make these two docker bash commands execute synchronously

bashdockerMySQL

I am automating the setup of dev environments for my app and when I run these two commands manually from the command line I have to wait around 10 seconds after running the first one to run the second one.

# command one (run the mysql docker container)
docker run -p 3306:3306 --name mysql-container-name -e MYSQL_ROOT_PASSWORD=secret -e MYSQL_DATABASE=mydbname -d mysql:latest

# command two (import data into created db)
docker exec -i mysql-container-name mysql mydbname < ./dev-db.sql --password=secret

I am trying to automate these two commands into a bash alias so I can just do db-setup but even when I separate the commands with the && the second command executes too quickly (before the mysql container is fully setup apparently) because I will get this error:

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)

Any idea how I can get the second command only when the first one is completely finished with everything it needs to do?

Best Answer

If a shell script is acceptable, perhaps the easiest way is to try the upload, wait 5 seconds and try the upload again until it works. Something like this:

docker run -p 3306:3306 --name mysql-container-name -e MYSQL_ROOT_PASSWORD=secret -e MYSQL_DATABASE=mydbname -d mysql:latest
until [docker exec -i mysql-container-name mysql mydbname < ./dev-db.sql --password=secret]
    do
    sleep 5
    done
Related Topic