简体   繁体   English

使用 SQL 文件在 Docker 容器中创建 MYSQL 表

[英]Creating a MYSQL table in a Docker container with a SQL file

I have created a MySQL docker container with我创建了一个 MySQL docker 容器

sudo docker run -d --name db-mysql -e MYSQL_ROOT_PASSWORD=mypassword -e MYSQL_DATABASE=DB mysql

I have schema.sql to create the schema我有schema.sql来创建架构

DROP DATABASE IF EXISTS `DB`;
CREATE DATABASE `DB`;
USE `DB`;

DROP TABLE IF EXISTS `Occurrences`;
CREATE TABLE `Occurrences` (
  `IdOccurrence` int NOT NULL AUTO_INCREMENT,
  `Name` varchar(100) NOT NULL,
  `Min_probability` double NOT NULL,
  PRIMARY KEY (`IdOccurrence`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;
INSERT INTO `Occurrences` VALUES (1,'Frequent',20),(2,'Probable',10),(5,'Possible',1),(6,'Rare',0.1),(7,'Remote',0);

And try to import it (in Ubuntu 18.04) with并尝试导入它(在 Ubuntu 18.04 中)

sudo docker exec db-mysql mysql -uroot -pmypassword DB < schema.sql

However, I get this warning但是,我收到此警告

mysql: [Warning] Using a password on the command line interface can be insecure.

But the database DB remains empty.但是数据库 DB 仍然是空的。

Where is my error?我的错误在哪里?

As stated in the documentation for the docker image you can initialize a container with a sql script:如 docker 镜像文档中所述,您可以使用 sql 脚本初始化容器:

When a container is started for the first 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.此外,它将执行在 /docker-entrypoint-initdb.d 中找到的扩展名为 .sh、.sql 和 .sql.gz 的文件。 Files will be executed in alphabetical order.文件将按字母顺序执行。 You can easily populate your mysql services by mounting a SQL dump into that directory and provide custom images with contributed data.您可以通过将 SQL 转储装载到该目录中并提供带有贡献数据的自定义图像来轻松填充您的 mysql 服务。 SQL files will be imported by default to the database specified by the MYSQL_DATABASE variable.默认情况下,SQL 文件将导入由 MYSQL_DATABASE 变量指定的数据库。

So if you start your container with the following it should startup with your schema:因此,如果您使用以下内容启动容器,它应该使用您的架构启动:

sudo docker run -d --name db-mysql -e MYSQL_ROOT_PASSWORD=mypassword -e MYSQL_DATABASE=DB -v $PWD/schema.sql:/docker-entrypoint-initdb.d/schema.sql mysql

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM