Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

362
Views
Lost connection to MySQL server when creating database from script in a Docker container

I'm setting an script to configure Docker environments for developer local machines. A specifically part of the script consists to create a temporary container with a local volume to set the database i'll use in 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 the exit with exit command after the first command and i execute the second one by my hand, directly in the terminal, it works and creates me the database.

Any idea what is this happening?

thanks in advance,

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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

I'm assuming you have written a shell script. Try the following 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 the second line having sleep 10. Basically this will create a delay of 10 seconds before executing the next command. Try varying the sleep time to higher 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 works. Thats because by the time you tried running manually, the container has initialised mysql. Try running the docker run command in one terminal window. Once the container starts, try running the mysql command immediately in another terminal window to see if it works as quickly as you expected.

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!