为什么我的 docker-entrypoint-initdb.d 脚本(在 docker-compose.yml 中指定)没有被执行来初始化一个新的 MySQL 实例?

2021-12-26 00:00:00 docker docker-compose mysql init

我从 这个答案/docker-entrypoint-initdb.d 目录>,并阅读How to use this image" MySQL 文档的初始化一个新实例"部分.但是当我在包含下面的 docker-compose.yml 文件的目录中运行 docker-compose up 时,我的数据库没有初始化.

I found out about the /docker-entrypoint-initdb.d directory from this answer, and also read the "Initializing a fresh instance" section of the "How to use this image" MySQL documentation. But when I run docker-compose up in the directory containing the docker-compose.yml file below, my database isn't initialized.


services:

# Use root/root as MySQL user/password credentials
  db:
    image: mysql
    restart: always
    environment:
      MYSQL_ROOT_PASSWORD: root
      MYSQL_USER: root
      MYSQL_PASSWORD: root
      MYSQL_DATABASE: db
    volumes:
      - ./mysql/data:/var/lib/mysql
      - ./mysql/init:/docker-entrypoint-initdb.d/:ro

  adminer:
    image: adminer
    restart: always
    ports:
      - 8080:8080

我确认./mysql/init 目录包含一个名为init.sql 的文件.我确认在清空 ./mysql/data 目录并运行 docker-compose up 后,会创建一个 db 数据库.但是没有填充数据库,除非我在 Adminer 中手动执行脚本.(我单击导入",然后选择文件并按执行"按钮.)

I confirmed the ./mysql/init directory contains a file named init.sql. And I confirmed that after I empty the ./mysql/data directory and run docker-compose up, that a db database is created. But the database is not populated, unless I manually execute the script in Adminer. (I click on "Import", then choose the file and press the Execute button.)

我在运行 docker-compose up 后在控制台输出中查找消息,表明尝试运行 init.sql 并且找不到任何东西.

I looked for messages in the console output after running docker-compose up that indicate an attempt to run init.sql and can't find anything.

更新:MySQL 版本为 8.0.19.

Update: The MySQL version is 8.0.19.

推荐答案

魔鬼藏在细节中...

您的环境变量中有 root 的双重定义.root 用户默认创建,密码来自 MYSQL_ROOT_PASSWORD.然后您要求创建第二个普通"用户...使用完全相同的名称和密码(即使用 MYSQL_USERMYSQL_PASSWORD)

You have a double definition of root in your env vars. root user is created by default with password from MYSQL_ROOT_PASSWORD. You then ask to create a second "normal" user... with the exact same name and password (i.e. with MYSQL_USER and MYSQL_PASSWORD)

如果你仔细查看你的启动日志,你会看到一个错误

If you look carefully at your startup log, you will see an error

db_1       | ERROR 1396 (HY000) at line 1: Operation CREATE USER failed for 'root'@'%'

这实际上会停止对 docker-entrypoint-initdb.d 中的 init 文件的进一步处理,并继续进行其余的映像启动过程(即在临时服务器上初始化后重新启动 mysql).

This actually stops further processing of your init files in docker-entrypoint-initdb.d and goes on with the rest of the image startup process (i.e. restarting mysql after initialization on temporary server).

只需将 MYSQL_USERMYSQL_PASSWORD 放到你的环境变量中,或者设置一个不同于 root 的用户,你会立即看到你的 init 文件被处理(不要忘记再次清空您的数据目录).

Simply drop MYSQL_USER and MYSQL_PASSWORD in your env vars, or set a different user than root and you will immediately see your init files processed (don't forget to empty your data dir again).

相关文章