mysql - 创建、填充和使用 Docker 卷

标签 mysql docker mariadb docker-volume

过去几天我一直在使用 Docker,希望很快就能将我的 Python-MySQL Web 应用程序迁移到 Docker。

推论是我需要使用 Docker 卷,并且最近被难住了。我可以直接创建一个卷

$ dockervolume create my-vol

或者间接通过在 docker run 调用中引用不存在的卷,但我无法弄清楚如何使用我的 .sql 数据库文件填充这些卷,而不通过 Dockerfile 中的 COPY 调用复制文件。

我尝试直接在包含 .sql 文件的目录中创建卷(上面提到的第一种方法),并在“docker run”调用中安装包含 .sql 文件的目录,这确实会将 .sql 文件移动到容器(我通过在容器内导航 bash shell 看到了它),但是当运行连接到包含数据库的 mariadb 容器的 mariadb 容器时(如 mariadb docker 自述文件中建议的那样),它只有标准数据库 (information_schema 、mysql、性能模式)

如何创建包含预先存在的 .sql 数据库的卷?

最佳答案

在 docker 容器中使用 mariadb 时,该镜像支持运行 .sql文件作为容器首次启动的一部分。这允许您在数据可供访问之前将其推送到数据库中。

来自the mariadb documentation :

Initializing a fresh instance

When a container is started for thefirst 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 mariadb 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.

这意味着如果你想将数据注入(inject)到容器中,当它第一次启动时。在你的Dockerfile , COPY .sql将文件放入路径 /docker-entrypoint-initdb.d/myscript.sql 的容器中- 它将在您在环境变量 MYSQL_DATABASE 中指定的数据库上调用.

像这样:

FROM mariadb
COPY ./myscript.sql /docker-entrypoint-initdb.d/myscript.sql

然后:

docker run -e MYSQL_DATABASE=mydb mariadb

接下来的问题是如何管理数据库存储。您基本上有两个选择:

  1. 创建一个到主机的卷绑定(bind),mariadb 在该主机上存储数据库。这将使您能够从主机轻松访问数据库存储文件。

使用 docker run 的示例:

docker run -v /my/own/datadir:/var/lib/mysql mariadb
  1. 创建一个 docker 卷并将其绑定(bind)到容器中的存储位置。这将是由 docker 管理的卷。该卷将在容器重新启动之间保留数据。
docker volume create my_mariadb_volume
docker run -v my_mariadb_volume:/var/lib/mysql mariadb

docs for the mariadb 中也涵盖了此内容 docker 图像。如果您要使用此图像,我建议您从上到下阅读。

关于mysql - 创建、填充和使用 Docker 卷,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55034104/

相关文章:

mysql - 如何在现有列中添加前导零?

ubuntu - 如何从 Docker 提供 Harp/nginx 页面?

Docker 查看历史日志

mysql - mysql和mariadb性能不同

mysql - 查询中存在多个 LIKE 语句

c# - Linq .Count() 来自另一个带有内连接的表 (C#)

mysql - PK 和 MySQL 中另一个字段的表更新偶尔会很慢

mysql - 如果不同列中不存在数据,则允许重复记录

c# - 从 C# Windows 窗体调用 PHP Web 服务

node.js - 无法在 docker 容器中列出 pm2