docker启动时初始化 mysql 数据

1,074 阅读1分钟

官网介绍 mysql 容器初始化内容:

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.

即容器在首次启动时,会执行 /docker-entrypoint-initdb.d 文件夹下 带 .sh, .sql and .sql.gz 后缀的文件。

因此,我们需要把需要初始化的数据放入 /docker-entrypoint-initdb.d 文件夹下:

FROM mysql:8.0.27

# Environment Variables

# MYSQL_ROOT_PASSWORD 必需。为 MySQL root超级用户帐户设置的密码。
# MYSQL_DATABASE 可选。指定要在映像启动时创建的数据库的名称。

ENV MYSQL_DATABASE=mall \ 
    MYSQL_ROOT_PASSWORD=123456

ADD mall.sql /docker-entrypoint-initdb.d

EXPOSE 3306

再执行 build 和 run 命令运行

$ docker build -t second-init-mysql .
$ docker run --name second-init-mysql -p 3306:3306 -e MYSQL_ROOT_PASSWORD=123456 second-init-mysql

另附上导出数据库的命令:

mysqldump -h -u -p --no-data > schema.sql

踩坑:导出数据库使用的 mysql 版本要和导入数据库的版本保持一致,不然有出错的可能。

参考:

1、hub.docker.com/_/mysql (/docker-entrypoint-initdb.d)

2、stackoverflow.com/questions/2… (initialize a MySQL database with schema)