0

In my Dockerfile

FROM mysql:5.7

ADD ./mysql_scripts /mysql_scripts 
WORKDIR /mysql_scripts
RUN mysql -u root -p < create_user.sql &&\
    mysql -u root -p < create_database.sql &&\
    mysql -u root -p < create_tables.sql

EXPOSE 3306

but when I build that image I have problem like:Enter password: ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock'

2 Answers 2

8

You cannot run those mysql commands, because the container is not running yet, so neither is MySQL.

What you can do is copy your .sql files to /docker-entrypoint-initdb.d. MySQL will run all .sql, .sql.gz and .sh located in this directory after initialization, which would result in the following Dockerfile:

FROM mysql:5.7

COPY ./mysql_scripts /docker-entrypoint-initdb.d

EXPOSE 3306

More information can be found on the dockerhub page of mysql

Sign up to request clarification or add additional context in comments.

Comments

4

You can not import database at build time, as every RUN command run in separate shell plus MySQL process also not ready to accept the connection.

You can take benefits from docker entrypoint that does these out of the box.

COPY create_user.sql  /docker-entrypoint-initdb.d/
COPY create_database.sql /docker-entrypoint-initdb.d/
COPY create_tables.sql /docker-entrypoint-initdb.d/

So when the container started it will run the above script in alphabetical order

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.

mysql-docker-init-db

Also you use MYSQL_USER to create user.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.