mysql - 在 Dockerfile 中创建 MySQL 数据库时出错

标签 mysql docker

我想创建一个简单的容器,其中包含一个带有初始化数据库的 MySQL 服务器。我的 Dockerfile 目前看起来像这样:

FROM ubuntu:16.10

RUN apt-get update

# install MySQL; root user with no password
ENV DEBIAN_FRONTEND noninteractive
RUN apt-get install -y mysql-server mysql-client

RUN service mysql start
RUN mysqladmin -u root create mydb

CMD [ "bash" ]

但是,当我通过 docker build -t mysql-test 构建图像时。 我收到以下错误:

Step 7 : RUN mysqladmin -u root create mydb
 ---> Running in a35c3d176d4f
mysqladmin: connect to server at 'localhost' failed
error: 'Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (111)'
Check that mysqld is running and that the socket: '/var/run/mysqld/mysqld.sock' exists!
The command '/bin/sh -c mysqladmin -u root create mydb' returned a non-zero code: 1

当我对要创建数据库的行添加注释时 (RUN mysqladmin -u root create mydb),我可以构建镜像,启动它,然后从命令行执行 mysqladmin 命令:

# this works
> docker run -it mysql-test
root@...> service mysql start
root@...> mysqladmin -u root create mydb

为什么在 Dockerfile 中创建数据库时会出现错误?谢谢!

最佳答案

阅读 RUN instruction 的文档说清楚:

The RUN instruction will execute any commands in a new layer on top of the current image and commit the results. The resulting committed image will be used for the next step in the Dockerfile.

所以每个运行指令都会创建一个新图像,启动 MySQL 服务器和创建数据库应该合并在同一个 RUN 指令中:

RUN service mysql start && mysqladmin -u root create mydb

这就解决了。

关于mysql - 在 Dockerfile 中创建 MySQL 数据库时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41601146/

相关文章:

php - 如何检索mysql表列中的数据?

docker - 如何使用cirrus-ci创建docker multiarch list ?

mysql - 自定义 Docker MySQL 构建无法运行

mysql - 我可以阻止 MySQL 索引特定值吗?

c# - 为一个值选择多个表

mysql : Not allowed to return a result set from a function

linux - 如何将一个进程作为 docker 的背景

docker - 让 docker 容器连接到网络设备

docker - 在centos7上安装Kubernetes

mysql - 生成字母数字 ID VB.NET 时出错