Docker新建MySQL容器时自动初始化数据

场景

需要写一个 Dockerfile 来实现创建 mysql 容器的时候,导入已经准备好的 .sql 文件.

解决

刚开始自己模拟过程写,最后发现不行,仔细看文档,原来官方已经写了。 文档

Initializing a fresh instance
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. You can easily populate your mysql 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.

所以可以写以下 Dockerfile

FROM mysql:latest
ENV MYSQL_ROOT_PASSWORD 123456
ENV MYSQL_USER=example
ENV MYSQL_PASSWORD=123456
COPY example.sql /docker-entrypoint-initdb.d/

然后 docker build -t mysql-test . && docker run -d mysql-test,此时进入容器中已经可以看见 example.sql 已经导入到了数据库

在实际使用中,这么简单的东西往往不需要使用 Dockerfile,可以在编写 docker-compose.yml 文件中加上:

volumes:
  - ./docker/mysql/scripts:/docker-entrypoint-initdb.d
  - ./mysql_data:/var/lib/mysql

参考资料

  1. https://stackoverflow.com/questions/38504257/mysql-scripts-in-docker-entrypoint-initdb-are-not-executed
©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页