0

I implemented the following shell script which uses the official mysql Docker image to create a Docker container and then, creates several databases.

#!/bin/bash

mysql_apim_password=root
mysql_apim_host=localhost
mysql_apim_username=root


if [ ! "$(docker ps -q -f name=mysql-5.7)" ]; then
    echo -e "---> Starting MySQL docker container..."
    container_id=$(docker run -d --name mysql-5.7 -p 3306:3306 -e MYSQL_ROOT_HOST=% -e MYSQL_ROOT_PASSWORD=$mysql_apim_password mysql:5.7.19)
    echo $container_id

    docker ps -a
    echo -e "---> Waiting for MySQL to start on 3306..."
    while ! nc -z $mysql_apim_host 3306; do
        sleep 1
        printf "."
    done
    echo ""
    echo -e "---> MySQL Started."
else
    echo -e "---> MySQL is already running..."
fi

#sleep 10

echo -e "---> Creating databases..."
docker exec -it mysql-5.7 mysql -h$mysql_apim_host -u$mysql_apim_username -p$mysql_apim_password -e "DROP DATABASE IF EXISTS "am_db"; DROP DATABASE IF EXISTS "um_db"; DROP DATABASE IF EXISTS "reg_db"; CREATE DATABASE "am_db"; CREATE DATABASE "um_db"; CREATE DATABASE "reg_db";"

When executing the above script without sleeping prior to databases creation, I encounter the following error:

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

I found this generally accepted set of solutions for the above issue and many others, but none of them have helped me so far.

I did some quick tests by accessing the running Docker container within the first few seconds after the container creation to check if the defined socket file has not been created, but I find that it is always present.

When I sleep prior to database creation (uncomment the sleep 10 in the above code segment), the procedure executes without any issues.

But what causes the above discussed issue, in Docker containers?

Chiranga Alwis
  • 1,049
  • 1
  • 25
  • 47
  • So you read one link. What about the other 7 that are listed in the **Related** list over there **===>>>**, or the dozens of others that can be found with a search for that error message? – Ken White Jan 06 '18 at 21:13
  • I just pointed out the one based on most votes, but I tried almost all of them. Found of a similar problem (https://stackoverflow.com/questions/35479475/docker-mysql-commands-within-dockerfile-using-run-error-2002?rq=1) but this did not help either. – Chiranga Alwis Jan 06 '18 at 21:28

0 Answers0