docker 安装 MySQL

步骤1:创建宿主机 MySQL 相关文件目录,均放在/data/software/mysql/目录中

mkdir -p /data/software/mysql/log
mkdir -p /data/software/mysql/data
mkdir -p /data/software/mysql/conf
mkdir -p /data/software/mysql/mysql-files

步骤2:在 /data/software/mysql/conf 中创建 my.cnf 配置文件

[mysqld]
character-set-server=utf8
collation-server=utf8_bin
default-storage-engine=INNODB
secure-file-priv=/var/lib/mysql
max_allowed_packet=512M
innodb_log_file_size=2GB
transaction-isolation=READ-COMMITTED
binlog_format=row

步骤3:docker 运行 mysql 宿主服务器 3308 端口映射到 docker 容器中的 3306 端口,root用户密码为123456

docker run -p 3308:3306 --name mysql --restart=always --privileged=true \
-v /data/software/mysql/log:/var/log/mysql \
-v /data/software/mysql/data:/var/lib/mysql \
-v /data/software/mysql/conf:/etc/mysql \
-v /data/software/mysql/mysql-files:/var/lib/mysql-files \
-e MYSQL_ROOT_PASSWORD='123456' -d mysql:latest
步骤4:设置 root 账号任意IP访问,连接或者进入mysql容器修改配置
1 查看docker容器id
docker ps
CONTAINER ID   IMAGE          COMMAND                  CREATED         STATUS         PORTS        NAMES
249029fb9fd2   mysql:latest   "docker-entrypoint.s…"   4 minutes ago   Up 4 minutes   33060/tcp, 0.0.0.0:3308->3306/tcp, :::3308->3306/tcp   mysql
2 根据id进入容器
docker exec -it --privileged=true --user root 249029fb9fd2 /bin/bash
3 进入mysql
mysql -uroot -p123456
4 进入用户数据库
use mysql;
5 查看用户表
select user,host from user;
+------------------+-----------+
| user             | host      |
+------------------+-----------+
| root             | %         |
| mysql.infoschema | localhost |
| mysql.session    | localhost |
| mysql.sys        | localhost |
| root             | localhost |
+------------------+-----------+
5 rows in set (0.00 sec)
由于这里root的host("%") 默认可以由任何IP访问,故直接退出即可,否则看第6步
6 设置 root 账号任意IP访问:

update user set Host='%' where User='root';
flush privileges; #立即生效

步骤5:现在可以ip加端口进行远程连接(这里宿主机的ip为172.31.144.211)

mysql -h 172.31.144.211 -P3308 -uroot -p123456

步骤6:将正在运行的mysql容器设为自启动

# 将正在运行的容器设为自启动
# docker update --restart=always 容器名或容器ID
docker update --restart=always <CONTAINER ID>
# 这里将mysql设置为自启动
docker update --restart=always 249029fb9fd2

# 将自启动的容器取消自启动
# docker update --restart=no 容器名或容器ID
docker update --restart=no <CONTAINER ID>
# 例如取消mysql的自启动
docker update --restart=no 249029fb9fd2

人生不作安期生,醉入东海骑长鲸