设置 MySQL 并在 Dockerfile 中导入转储 [英] Setting up MySQL and importing dump within Dockerfile

查看:39
本文介绍了设置 MySQL 并在 Dockerfile 中导入转储的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为我的 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

这篇关于设置 MySQL 并在 Dockerfile 中导入转储的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆