0

I've read recent post Setting up MySQL and importing dump within Dockerfile but couldn't find an answer.

What I want is to build custom mysql image with created database, users and some other data. Here is my Dockerfile(simplified):

    FROM mysql:5.7

    ENV MYSQL_ROOT_PASSWORD=root

    RUN service mysql start && \
       mysql -uroot -p$MYSQL_ROOT_PASSWORD -e "CREATE DATABASE mydb;" && \
       mysql -uroot -p$MYSQL_ROOT_PASSWORD -e "SHOW databases;" && \   
       service mysql stop

ENTRYPOINT service mysql start && /bin/sh   

Image is built successfully and mydb database is listed as output of "SHOW DATABASES". But when I run container based on this image I see that root password is empty and mydb database is missing.

How can I fix that? Thanks?

Sergiy
  • 1,854
  • 4
  • 22
  • 34

1 Answers1

0

You can use init scripts. It much more easier then Runing and Stopping mysql into RUN command

Initializing a fresh instance

When a container is started for the first time, a new database with the specified name will be created and initialized with the provided configuration variables. Furthermore, it will execute files with extensions .sh, .sql and .sql.gz that are found in /docker-entrypoint-initdb.d. Files will be executed in alphabetical order. You can easily populate your mysql services by mounting a SQL dump into that directory and provide custom images with contributed data. SQL files will be imported by default to the database specified by the MYSQL_DATABASE variable.

Bukharov Sergey
  • 9,767
  • 5
  • 39
  • 54
  • Thank you, Sergey. I will try that. But why my database created at RUN instruction was lost? Does it mean it doesn't make sense to initialize database-related data before first container run? – Sergiy Oct 13 '17 at 09:40
  • This is good question. Could you show me `Dockerfile` where you use that base image? – Bukharov Sergey Oct 13 '17 at 09:45
  • Sergey, I specified Docker file contents in the question description – Sergiy Oct 13 '17 at 13:13
  • Yes, you show me base `Dockerfile`. But could you show also how do you use this base image? – Bukharov Sergey Oct 13 '17 at 13:15
  • I just run it using the following command: docker run -it mysql_db – Sergiy Oct 13 '17 at 13:19
  • Here is updated Dockerfile that shows MySQL databases during container startup: FROM mysql:5.7 ENV MYSQL_ROOT_PASSWORD=root RUN service mysql start && \ mysql -uroot -p$MYSQL_ROOT_PASSWORD -e "CREATE DATABASE mydb;" && \ mysql -uroot -p$MYSQL_ROOT_PASSWORD -e "SHOW databases;" && \ service mysql stop ENTRYPOINT service mysql start && mysql -uroot -p$MYSQL_ROOT_PASSWORD -e "SHOW databases;" – Sergiy Oct 13 '17 at 13:20