如何在docker-compose-now.yml的entrypoint中配置MySQL认证修复语句?
I’ve run into this exact issue before—MySQL 8.0+ uses caching_sha2_password by default, which older MySQL client libraries don’t support. The SQL you mentioned will fix the auth mode for the root user, and here are two clean ways to integrate it into your docker-compose-now.yml:
Option 1: Use an Entrypoint Override (Quick but Less Elegant)
You can override the MySQL container’s entrypoint to run your SQL after the database starts. Just make sure to keep the default entrypoint logic intact so MySQL boots properly:
version: '3.8' services: mysql: image: mysql:8.0 # Adjust to your MySQL version environment: MYSQL_ROOT_PASSWORD: "" # Match the empty password in your SQL entrypoint: - sh - -c - | # Start MySQL in the background docker-entrypoint.sh mysqld & # Wait a few seconds for the server to initialize sleep 5 # Run your auth mode fix SQL mysql -uroot -p'' -e "use mysql; update user set authentication_string=password(''), plugin='mysql_native_password' where user='root';" # Wait for the MySQL process to keep the container running wait
Note: The sleep 5 is a quick hack to wait for MySQL to start—if your server takes longer to initialize, you might need to increase this value.
Option 2: Use MySQL's Built-in Initialization Script (Recommended)
MySQL’s official image automatically runs any scripts in the /docker-entrypoint-initdb.d/ directory on first startup. This is the cleaner, more reliable approach:
- Create a new file named
init-mysql.sqlin the same directory as yourdocker-compose-now.ymlwith this content:
USE mysql; UPDATE user SET authentication_string=password(''), plugin='mysql_native_password' WHERE user='root'; FLUSH PRIVILEGES; # Don't forget this to apply changes immediately
- Update your
docker-compose-now.ymlto mount this script into the container:
version: '3.8' services: mysql: image: mysql:8.0 environment: MYSQL_ROOT_PASSWORD: "" volumes: - ./init-mysql.sql:/docker-entrypoint-initdb.d/init-mysql.sql
Important Note
If you’ve already started the MySQL container before, you’ll need to delete the existing volume (where MySQL stores its data) for the initialization script to run. Use this command to clean up:
docker volume rm <your-mysql-volume-name>
You can find your volume name with docker volume ls.
内容的提问来源于stack exchange,提问作者user8608046

