设置 MySQL 并在 Dockerfile 中导入转储

Setting up MySQL and importing dump within Dockerfile(设置 MySQL 并在 Dockerfile 中导入转储)
本文介绍了设置 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 中导入转储的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Hibernate reactive No Vert.x context active in aws rds(AWS RDS中的休眠反应性非Vert.x上下文处于活动状态)
Bulk insert with mysql2 and NodeJs throws 500(使用mysql2和NodeJS的大容量插入抛出500)
Flask + PyMySQL giving error no attribute #39;settimeout#39;(FlASK+PyMySQL给出错误,没有属性#39;setTimeout#39;)
auto_increment column for a group of rows?(一组行的AUTO_INCREMENT列?)
Sort by ID DESC(按ID代码排序)
SQL/MySQL: split a quantity value into multiple rows by date(SQL/MySQL:按日期将数量值拆分为多行)