过去几天我一直在使用 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
文件作为容器首次启动的一部分。这允许您在数据可供访问之前将其推送到数据库中。
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 theMYSQL_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
接下来的问题是如何管理数据库存储。您基本上有两个选择:
- 创建一个到主机的卷绑定(bind),mariadb 在该主机上存储数据库。这将使您能够从主机轻松访问数据库存储文件。
使用 docker run 的示例:
docker run -v /my/own/datadir:/var/lib/mysql mariadb
- 创建一个 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/