使用docker安装mysql服务

时间:2023-12-12 17:16:50

使用docker官方镜像安装mysql服务

1 拉取mysql镜像,采用网易加速地址

docker pull hub.c.163.com/library/mysql:5.7

2 重命名镜像名

docker tag hub.c.163.com/library/mysql:5.7 mysql:5.7

3. 创建用于挂载的目录

[root@WSyHRQ171356 mysql]# mkdir -p /mysql/datadir /mysql/conf.d

/mysql/datadir #用于挂载mysql数据文件

/mysql/conf.d #用于挂载mysql配置文件

4. 使用镜像创建容器

[root@WSyHRQ171356 mysql]# docker run -d -p 3306:3306 --name mysql -v /mysql/datadir:/var/lib/mysql -v /mysql/conf.d:/etc/mysql/conf.d -e MYSQL_ROOT_PASSWORD=mysql密码 mysql:5.7

命令解析:

-d:后台运行容器

-p:映射宿主主机端口

--name:容器名

-v:挂载宿主目录到容器目录

-e:设置环境变量,此处指定root密码

5. 设置mysql默认编码

[root@WSyHRQ171356 mysql]# vi /mysql/conf.d/my.cnf

内容如下:

[mysql]
default-character-set = utf8
[mysqld]
default-time-zone=timezone
default-time-zone = '+8:00'
skip-name-resolve #跳过DNS解析,加快远程连接速度
character_set_server=utf8
init_connect='SET NAMES utf8'
sql_mode=STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION

6. 重启mysql

[root@WSyHRQ171356 mysql]# docker restart mysql

7. 进入mysql查询编码

[root@WSyHRQ171356 mysql]# docker exec -it mysql bash
root@29ac5990c680:/# mysql -uroot -p
mysql> show variables like 'character%';
+--------------------------+----------------------------+
| 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.00 sec)

8. 创建mysql远程用户

mysql> GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY '密码' WITH GRANT OPTION;

9. 刷新生效

flush privileges;

10. 最后回到主机重启mysql即可

mysql> quit
Bye
root@29ac5990c680:/# exit
[root@WSyHRQ171356 mysql]# docker restart mysql
mysql
[root@WSyHRQ171356 mysql]#