设置 MySQL 并在 Dockerfile 中导入转储

2021-11-20 00:00:00 docker mysql

我正在尝试为我的 LAMP 项目设置 Dockerfile,但在启动 MySQL 时遇到了一些问题.我的 Dockerfile 上有以下几行:

I'm trying to setup a Dockerfile for my LAMP project, but i'm having a few problems when starting MySQL. I have the folowing lines on my Dockerfile:

VOLUME ["/etc/mysql", "/var/lib/mysql"]
ADD dump.sql /tmp/dump.sql
RUN /usr/bin/mysqld_safe & sleep 5s
RUN mysql -u root -e "CREATE DATABASE mydb"
RUN mysql -u root mydb < /tmp/dump.sql

但我不断收到此错误:

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

关于如何在 Dockerfile 构建期间设置数据库创建和转储导入的任何想法?

Any ideas on how to setup database creation and dump import during a Dockerfile build?

推荐答案

Dockerfile 中的每条 RUN 指令都在不同的层中执行(如 RUN 的文档.

Each RUN instruction in a Dockerfile is executed in a different layer (as explained in the documentation of RUN).

在您的 Dockerfile 中,您有三个 RUN 指令.问题是 MySQL 服务器只在第一次启动.在其他情况下,没有 MySQL 正在运行,这就是为什么您在 mysql 客户端出现连接错误的原因.

In your Dockerfile, you have three RUN instructions. The problem is that MySQL server is only started in the first. In the others, no MySQL are running, that is why you get your connection error with mysql client.

要解决此问题,您有两种解决方案.

To solve this problem you have 2 solutions.

RUN /bin/bash -c "/usr/bin/mysqld_safe --skip-grant-tables &" && \
  sleep 5 && \
  mysql -u root -e "CREATE DATABASE mydb" && \
  mysql -u root mydb < /tmp/dump.sql

解决方案 2:使用脚本

创建一个可执行脚本init_db.sh:

#!/bin/bash
/usr/bin/mysqld_safe --skip-grant-tables &
sleep 5
mysql -u root -e "CREATE DATABASE mydb"
mysql -u root mydb < /tmp/dump.sql

将这些行添加到您的 Dockerfile:

Add these lines to your Dockerfile:

ADD init_db.sh /tmp/init_db.sh
RUN /tmp/init_db.sh

相关文章