搭建mysql环境
1 下载mysql镜像
docker pull mysql:5.7
2 运行刚下载的mysql镜像文件
# 运行该命令之前可以使用`docker images`是否下载成功
docker run -p 3307:3306 --name mysql5.7 -v /mysql/conf:/etc/mysql/conf.d -v /mysql/logs:/logs -v /mysql/data:/var/lib/mysql -e MYSQL_ROOT_PASSWORD=123 -itd mysql:5.7
上面的意思是将mysql
在后台启动运行, 并且这个mysql
是运行在宿主机3307端口上的,等会django
连接的也是这个端口, --name 是将这个mysql
应用取了个别名。3个-v是指定容器中的mysql
的相关文件路径与宿主机路径的映射关系,这样便能通过修改宿主机的配置文件而达到修改容器中的mysql
的配置了。-e 指定的是进入容器后的mysql
的初始密码为123。
3 远程连接mysql
$ mysql -uroot -p123 -h 服务器ip地址 -P 3307
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
| sys |
+--------------------+
4 rows in set (0.04 sec)
# 上面可以登陆上, 也能正常查看数据库。但是数据库的默认编码方式还需要修改
mysql> show global variables like \'%char%\';
+--------------------------+----------------------------+
| Variable_name | Value |
+--------------------------+----------------------------+
| character_set_client | latin1 |
| character_set_connection | latin1 |
| character_set_database | latin1 |
| character_set_filesystem | binary |
| character_set_results | latin1 |
| character_set_server | latin1 |
| character_set_system | utf8 |
| character_sets_dir | /usr/share/mysql/charsets/ |
+--------------------------+----------------------------+
8 rows in set (0.03 sec)
4 修改服务器的配置文件
vim /mysql/conf/mysql.cnf
[client]
default-character-set = utf8
[mysqld]
character-set-server = utf8
collation-server = utf8_general_ci
init_connect=\'SET NAMES utf8\'
lower_case_table_names = 1
slow_query_log_file = /logs/slow.log
[mysql]
default-character-set = utf8
上面的配置主要是修改默认的编码方式,其他更加详细的配置可以参考
重启mysql服务
docker restart mysql5.7
修改后具体的结果如下所示:
mysql> show global variables like \'%char%\';
+--------------------------+----------------------------+
| Variable_name | Value |
+--------------------------+----------------------------+
| character_set_client | utf8 |
| character_set_connection | utf8 |
| character_set_database | utf8 |
| character_set_filesystem | binary |
| character_set_results | utf8 |
| character_set_server | utf8 |
| character_set_system | utf8 |
| character_sets_dir | /usr/share/mysql/charsets/ |
+--------------------------+----------------------------+
8 rows in set (0.04 sec)