Lost connection to MySQL server while creating database from script in Docker container

I am installing a script to set up Docker environments for local development machines. The specific part of the script is to create a temporary container with a local volume to install the database, which I will use in the next step. this is the code used in the script:

docker run -d --name mysql_temp -v ~/dev/mysql:/var/lib/mysql/data -e MYSQL_ROOT_PASSWORD=test -p 3306:3306 centos/mysql-57-centos7:latest

the next step in the script is this line:

mysql -u root -h 127.0.0.1 --protocol=tcp --password=test -e "CREATE DATABASE db_test;"

then the script returns me this error:

ERROR 2013 (HY000): Lost connection to MySQL server at 'reading initial communication packet', system error: 2


Curiously, if I force exit with the command exit

after the first command, and I execute the second one by hand, directly in the terminal, it works and creates a database for me.

Any idea what this is going on?

thanks in advance,

+3


source to share


1 answer


In your script, when the first line is executed, it creates a docker container. But it takes time to initialize the mysql server on the container. The script executes the second line without waiting for mysql to initialize. Hence, it cannot connect.

I assume you have written a shell script. Try to execute script.

docker run -d --name mysql_temp -v ~/dev/mysql:/var/lib/mysql/data -e MYSQL_ROOT_PASSWORD=test -p 3306:3306 centos/mysql-57-centos7:latest
sleep 10
mysql -u root -h localhost --protocol=tcp -ptest -e "CREATE DATABASE db_test;"

      



Note that the second line has sleep 10. Basically this will delay 10 seconds before executing the next command. Try changing your sleep time to a higher one if it still doesn't work.

Also change 127.0.0.1 to localhost and --password = test to -ptest

Note. ... You said that if you exit the script and run the mysql command manually, it will work. The point is that by the time you tried to start manually, the container had initialized mysql. Try running the docker run command in one terminal window. After starting the container, try running the mysql command immediately in another terminal window to see if it works as fast as you expected.

+2


source







All Articles