When using a Docker container to deploy a MySQL database, sometimes garbled Chinese characters may appear. This is because the default character set of MySQL is Latin1, and Chinese characters need to be encoded in UTF-8. This article will introduce how to solve the Chinese garbled problem of docker mysql.
1. Check the current MySQL character set
First, we need to check the current MySQL character set. You can use the following command after logging in to MySQL:
mysql> show variables like '%char%';
Among them, the character set related variables are:
2. Modify the MySQL character set to UTF-8
After checking that the current MySQL character set is Latin1, we need to modify it to UTF-8. This can be achieved in the following two ways:
In the MySQL configuration file (usually /etc/my.cnf or /etc/mysql/ my.cnf), add the following two lines:
[client] default-character-set=utf8 [mysqld] character-set-server=utf8
Among them, [client] is used to set the client character set to UTF-8, and [mysqld] is used to set the server character set to UTF-8. After the modification is completed, restart the MySQL service:
sudo service mysql restart
If you cannot modify the MySQL configuration file, you can manually modify the character set after connecting to MySQL. You can connect to MySQL through the following command:
mysql --default-character-set=utf8 -u用户名 -p密码 数据库名
After the connection is successful, execute the following commands in sequence to modify the character set:
SET character_set_client = utf8; SET character_set_connection = utf8; SET character_set_database = utf8; SET character_set_results = utf8; SET character_set_server = utf8;
After the modification is completed, exit MySQL and log in again to take effect.
3. Use the UTF-8 character set in the Docker container
Since MySQL in the Docker container runs based on the image, we need to set the UTF-8 character set in the image. The MySQL image can be built through the following Dockerfile:
FROM mysql:latest ENV MYSQL_ROOT_PASSWORD=root ENV MYSQL_DATABASE=test ENV MYSQL_CHARSET=utf8 ENV MYSQL_COLLATION=utf8_general_ci COPY ./init.sql /docker-entrypoint-initdb.d/
Among them, the ENV command is used to set environment variables, MYSQL_CHARSET is used to set the MySQL character set to UTF-8, and MYSQL_COLLATION is used to set the collation rule to utf8_general_ci. The initialization script init.sql is also copied to the image through the COPY command for automatic execution when starting the container.
4. Summary
Through the above three steps, we can use MySQL in the Docker container and set the character set to UTF-8 to avoid the problem of Chinese garbled characters. Of course, if you need to handle multilingual character sets, you need to make adjustments according to the specific situation. Hope this article can be helpful to everyone.
The above is the detailed content of docker mysql Chinese garbled code. For more information, please follow other related articles on the PHP Chinese website!