0

I'm trying to create a docker container with a prepared mysql database. This is the Dockerfile:

FROM mysql:5.7

COPY mysql_init.sh .
RUN chmod +x mysql_init.sh

RUN ./mysql_init.sh

And mysql_init.sh is as follows:

echo "Initialising db..."
  service mysql stop &
  sleep 5
  /usr/bin/mysqld_safe &
  sleep 5

  mysql -uroot -p${rootpasswd} -e "CREATE DATABASE IF NOT EXISTS ${db_name}";
  mysql -uroot -p${rootpasswd} -e "CREATE USER IF NOT EXISTS '${db_user}'@'%' IDENTIFIED BY '${db_password}'"; 
  mysql -uroot -p${rootpasswd} -e "GRANT ALL ON *.* TO '${db_user}'@'%'";

However, when I run docker build ., this is the result:

Sending build context to Docker daemon  13.31kB
Step 1/4 : FROM mysql:5.7
 ---> 7f0b364f5167
Step 2/4 : COPY mysql_init.sh .
 ---> 68ba65284dc2
Step 3/4 : RUN chmod +x mysql_init.sh
 ---> Running in 5671f52e4c06
Removing intermediate container 5671f52e4c06
 ---> ef21a79c102a
Step 4/4 : RUN ./mysql_init.sh
 ---> Running in 438164ef135e
Initialising db...
MySQL Community Server 5.7.30 is already stopped.
Logging to '/var/lib/mysql/438164ef135e.err'.
2020-06-03T21:27:04.326166Z mysqld_safe Starting mysqld daemon with databases from /var/lib/mysql
2020-06-03T21:27:07.889280Z mysqld_safe mysqld from pid file /var/run/mysqld/mysqld.pid ended
mysql: [Warning] Using a password on the command line interface can be insecure.
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)
mysql: [Warning] Using a password on the command line interface can be insecure.
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)
mysql: [Warning] Using a password on the command line interface can be insecure.
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)
Done.
Removing intermediate container 438164ef135e
 ---> aea19c03c1a9
Successfully built aea19c03c1a9

It looks like mysqld starts, then stops before the lines below it can run.

The same thing happens without the sleep 5 command, I added it because I thought mysqld hadn't finished initiating by the time the other commands ran.

I also tried setting mysql_init.sh as the entrypoint at the end of the Dockerfile, but the same thing happened.

What am I doing wrong?

Tuma
  • 603
  • 1
  • 7
  • 35
  • check the error logs and 5 maybe a little short to start a server – nbk Jun 03 '20 at 21:38
  • 1
    You'll have some trouble doing this in general, since the stock `mysql` image is configured in a way where you can't create a derived image with preloaded data. The techniques in [Setting up MySQL and importing dump within Dockerfile](https://stackoverflow.com/q/25920029/10008173) might help you, especially using the `/docker-entrypoint-initdb.d` directory. – David Maze Jun 03 '20 at 21:42

0 Answers0