MySQL Docker容器自动建库、用户后SQL脚本未完成数据库填充的问题求助
Alright, let's break down why your table creation and data population isn't working—you've got a small but critical misconfiguration here:
The Core Issue
You copied your SQL init script into the phpmyadmin container's /docker-entrypoint-initdb.d/ directory, but that directory is only used by the official MySQL Docker image to run initialization scripts on first startup. The phpmyadmin image doesn't care about that folder at all, so your script was never executed.
Step-by-Step Fix
Let's get your script running where it belongs—inside the MySQL container:
Ditch the custom phpmyadmin Dockerfile (or modify it)
You don't need to build a custom phpmyadmin image just for this init script. Either delete your Dockerfile entirely, or remove theCOPY DockerCreateAllTablesDBwithData.sql /docker-entrypoint-initdb.d/initdb.sqlline if you have other customizations for phpmyadmin.Mount your SQL script to the MySQL container
Update thevolumessection of yourdbservice indocker-compose.ymlto mount your local SQL file into the MySQL container's initialization directory:db: image: mysql:8-debian container_name: db restart: always networks: - network_app cap_add: - SYS_NICE environment: - MYSQL_ROOT_PASSWORD=password - MYSQL_USER=admin - MYSQL_PASSWORD=password - MYSQL_DATABASE=CantineTest - TZ='Europe/Paris' volumes: - mydatavolume:/var/lib/mysql # Add this line to mount your script - ./DockerCreateAllTablesDBwithData.sql:/docker-entrypoint-initdb.d/initdb.sqlReset your MySQL data volume (critical for existing setups)
The MySQL image only runs init scripts once, when the data volume is first created. If you've already started the container before, your existingmydatavolumewon't trigger the script again. Delete the old volume and restart:# Stop containers and delete volumes docker-compose down -v # Rebuild and start fresh docker-compose up -d
Extra Tips to Avoid Headaches
- Remove redundant database creation: Your SQL script has
create database CantineTest;, but you already setMYSQL_DATABASE=CantineTestin your docker-compose environment variables. This will cause a harmless but annoying "database already exists" error in logs—delete that line from your SQL script and just keepuse CantineTest;. - Verify execution: Check the MySQL container logs to confirm the script ran successfully:
Look for lines likedocker logs dbExecuting /docker-entrypoint-initdb.d/initdb.sql—if there are errors, they'll show up here too. - Check script encoding: Make sure your SQL file is saved in UTF-8 or a MySQL-compatible encoding to avoid unexpected parsing issues.
内容的提问来源于stack exchange,提问作者user19413311

