我目前被屏蔽了,我想在构建 Dockerfile 时构建一个数据库。但我得到了一个错误,我不明白为什么。感谢您的帮助。
这是我的 Dockerfile
FROM mariadb:latest
WORKDIR /sql-files
ADD sql/ /sql-files/
ENV MYSQL_ROOT_PASSWORD test123
ENV MYSQL_DATABASE testDB
ENV MYSQL_USER toto
ENV MYSQL_PASSWORD test123
RUN apt-get update && apt-get -y install vim && chmod +x insertDB.sh && sh insertDB.sh
EXPOSE 3306
这是我的 insertDB.sh
#!/bin/sh
/usr/bin/mysqld_safe --skip-grant-tables &
sleep 5
mysql --user=$MYSQL_USER --password=$MYSQL_PASSWORD $MYSQL_DATABASE < test.sql
最后是我的 test.sql 脚本
CREATE TABLE IF NOT EXISTS test (
id int NOT NULL AUTO_INCREMENT,
name varchar(32) NOT NULL,
PRIMARY KEY (id)
);
INSERT INTO test (name) VALUES
('Toto'),
('Jack'),
('Titi');
因此,当我使用命令 docker build -t maria .
执行 docker 文件时,我收到此错误:
Processing triggers for libc-bin (2.19-18+deb8u10) ...
171112 18:12:53 mysqld_safe Logging to syslog.
171112 18:12:54 mysqld_safe Starting mysqld daemon with databases from /var/lib/mysql
ERROR 1049 (42000): Unknown database 'testDB'
The command '/bin/sh -c apt-get update && apt-get -y install vim && chmod +x insertDB.sh && sh insertDB.sh' returned a non-zero code: 1
我错过了什么?
最佳答案
使用mariadb image from dockerhub它比您尝试的更简单。
如“初始化新实例部分”中所述:
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. Files will be executed in alphabetical order.
因此,只需将 test.sql
脚本添加到 /docker-entrypoint-initdb.d
然后你的 Dockerfile 必须运行 mysqld 作为命令。
因此,我将仅在本地 sql
子目录中保留 test.sql
,并且我将使用此 Dockerfile
:
FROM mariadb:latest
ADD sql/ /docker-entrypoint-initdb.d
ENV MYSQL_ROOT_PASSWORD test123
ENV MYSQL_DATABASE testDB
ENV MYSQL_USER toto
ENV MYSQL_PASSWORD test123
RUN apt-get update && apt-get -y install vim
EXPOSE 3306
CMD ["mysqld"]
然后构建您的图像
docker build -t maria .
并运行容器(可能对映射端口有用)
docker run --name mariadb -ti -d -p 3306:3306 maria
它会创建 testDB
和用户 toto
,正如您使用 Dockerfiles 中的环境变量正确定义的那样(提醒您可以将它们覆盖为 -e
) > docker run
中的参数)。
关于docker - 无法在 Dockerfile 中构建 mariaDB 基础,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47252273/