1、查询容器ID

docker ps -a

[root@docker ~]# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
d8b9eadcc7e4 mysql:latest "docker-entrypoint.s…" 2 hours ago Up 3 minutes 0.0.0.0:3306->3306/tcp, :::3306->3306/tcp, 33060/tcp mysql

2、进入容器并登录数据库

[root@docker ~]# docker exec -it mysql bash
bash-4.4# mysql -uroot -p123456

mysql> show databases;

Database
information_schema
mysql
performance_schema
sys
test

mysql> use test;

mysql> show tables;

Tables_in_test
Dog
Movies
??

查询数据

mysql> select * from Dog;
IdName(???Weight????Height (???Type (??)Age (??)Color (??)
1Mike328???10?
2Sala6.540??15?
3??21.545??26?
4??1542???20?
5Boy5.524???6?

发现出现乱码’?‘

3、查询默认编码

mysql> show variables like '%char%';
Variable_nameValue
character_set_clientlatin1
character_set_connectionlatin1
character_set_databaseutf8mb4
character_set_filesystembinary
character_set_resultslatin1
character_set_serverutf8mb4
character_set_systemutf8mb3
character_sets_dir/usr/share/mysql-8.0/charsets/

需要将编码改为utf8mb3

4、修改my.cnf参数

将容器的my.cnf文件复制出来

[root@docker ~]# docker cp d8b9eadcc7e4:/etc/my.cnf /root/

编辑my.cnf文件,添加如下内容

[root@docker ~]# vi my.cnf

[mysql]
default-character-set=utf8

[mysqld]
collation-server = utf8_unicode_ci
init-connect='SET NAMES utf8'
character-set-server = utf8

[client]
default-character-set=utf8

将文件复制回去

docker cp /root/my.cnf d8b9eadcc7e4:/etc/

重启容器

docker restart mysql

再次查看编码发现修改成功

mysql> show variables like '%char%';
Variable_nameValue
character_set_clientutf8mb3
character_set_connectionutf8mb3
character_set_databaseutf8mb4
character_set_filesystembinary
character_set_resultsutf8mb3
character_set_serverutf8mb3
character_set_systemutf8mb3
character_sets_dir/usr/share/mysql-8.0/charsets/

查询数据

mysql> show tables;
Tables_in_test
Dog
Movies
域名
mysql> select * from Dog;
IdName(名字)Weight(体重)Height (身高)Type (品种)Age (月龄)Color (肤色)
1Mike328吉娃娃10
2Sala6.540柴犬15
3黑狮21.545藏獒26
4大圣1542牧羊犬20
5Boy5.524蝴蝶犬6

显示正常