无法通过Docker Image中的套接字错误连接到本地MySQL服务器

时间:2017-09-06 21:18:36

标签: mysql docker dockerfile

我正在创建包含一些示例数据的mysql图像。当我在图像创建期间尝试启动mysql进程时,我收到错误,以便我可以将数据放入图像中。以下是我的文件结构

[DockerFile]

FROM mysql:5.6.29

# MYSQL volumes
VOLUME ["/etc/mysql", "/var/lib/mysql"]

COPY data_dump.sql /tmp/

COPY init_db.sh /tmp/

RUN chmod -R 777 /tmp/init_db.sh

RUN chmod -R 777 /tmp/data_dump.sql

RUN /tmp/init_db.sh

EXPOSE 3306

[init_db.sh]

#!/bin/bash
echo "starting the bash command"
/usr/bin/mysqld_safe &
echo "started the mysqld_safe process"
sleep 15
mysql -u root -h localhost -e "CREATE DATABASE test"
echo "Done creating the test schema"
mysql -u root -h localhost test < /tmp/data_dump.sql
echo "Done creating the test data"

我收到以下错误:

started the mysqld_safe process
170906 13:56:49 mysqld_safe Logging to '/var/lib/mysql/bcad5a346f31.err'.
170906 13:56:49 mysqld_safe Starting mysqld daemon with databases from /var/lib/mysql
170906 13:56:49 mysqld_safe mysqld from pid file /var/run/mysqld/mysqld.pid ended
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)

Done creating the test schema
Done creating the test data
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)

1 个答案:

答案 0 :(得分:0)

我找到了一个解决方案,事实证明我的工作比我需要的要多。下面是我的DockerFile现在看起来像

<强> [DockerFile]

FROM mysql:5.6.29

# 1. Set up the environment variables
ENV MYSQL_ALLOW_EMPTY_PASSWORD yes
ENV MYSQL_DATABASE testDB
ENV MYSQL_USER root

# 2. copy the data dump file in the /docker-entrypoint-initdb.d/ location so that it gets executed by default
COPY data-dump.sql /docker-entrypoint-initdb.d/data-dump.sql

# 3. change the data location in the my.conf file in the docker, it is needed to create the data from the /docker-entrypoint-initdb.d/data-dump.sql dump file
# for mysql 5.7 if the below line doesn't work try: RUN sed -i 's|/var/lib/mysql|/var/lib/mysql-data|g' /etc/mysql/mysql.conf.d/mysqld.cnf
RUN sed -i 's|/var/lib/mysql|/var/lib/mysql-data|g' /etc/mysql/my.cnf

# 4. start the mysql process so that it creates the required data
RUN /entrypoint.sh mysqld & sleep 30 && killall mysqld

# 5. remove the dump file from the image to save image space
RUN rm /docker-entrypoint-initdb.d/data-dump.sql