学习并记录一下如何用docker部署MySQL
- 在Docker中搜索并下载MySQL8.0.x的最新版本
- 下载好后,在Images中就可以看到MySQL的镜像了
通过下面的命令也可以查看docker images
- 启动镜像,使用下面的命令就可以启动镜像了
解释:docker run -itd --name mysql8.0.34 -p 3306:3306 --privileged=true -e MYSQL_ROOT_PASSWORD=root mysql:8.0.34
- -i :即使没有连接,也要保持标准输入保持打开状态,一般与 -t 连用
- -t:分配一个伪tty,一般与 -i 连用
- -d:在后台运行容器,并且打印容器id
- –name:镜像名称
- -p:端口映射,容器内端口3306映射到容器外的3306上
- –privileged:为容器提供权限
- -e:设置镜像参数
- MYSQL_ROOT_PASSWORD:设置root用户的密码
- 此时,在容器内部已经初始化好了MySQL了,但是一般来说,我们需要把MySQL的配置文件和datadir挂在到docker外部,所以我们还需要后面的步骤
- 创建config和data目录
mkdir -p /Users/xxx/docker/data/mysql8.0.34/{config,data}
- 切换到config目录
cd /Users/xxx/docker/data/mysql8.0.34/config
- 把config文件从镜像内部复制出来
docker cp mysql8.0.34:/etc/my.cnf ./
- 确认config文件
cat my.cnf
# For advice on how to change settings please see # http://dev.mysql.com/doc/refman/8.0/en/server-configuration-defaults.html[mysqld] # # Remove leading # and set to the amount of RAM for the most important data # cache in MySQL. Start at 70% of total RAM for dedicated server, else 10%. # innodb_buffer_pool_size = 128M # # Remove leading # to turn on a very important data integrity option: logging # changes to the binary log between backups. # log_bin # # Remove leading # to set options mainly useful for reporting servers. # The server defaults are faster for transactions and fast SELECTs. # Adjust sizes as needed, experiment to find the optimal values. # join_buffer_size = 128M # sort_buffer_size = 2M # read_rnd_buffer_size = 2M# Remove leading # to revert to previous value for default_authentication_plugin, # this will increase compatibility with older clients. For background, see: # https://dev.mysql.com/doc/refman/8.0/en/server-system-variables.html#sysvar_default_authentication_plugin # default-authentication-plugin=mysql_native_password skip-host-cache skip-name-resolve datadir=/var/lib/mysql socket=/var/run/mysqld/mysqld.sock secure-file-priv=/var/lib/mysql-files user=mysql # 忽略表名大小写 lower_case_table_names=1pid-file=/var/run/mysqld/mysqld.pid [client] socket=/var/run/mysqld/mysqld.sock!includedir /etc/mysql/conf.d/
- 停掉并删除之前启动的MySQL镜像
docker stop mysql8.0.34 docker rm mysql8.0.34
- 重启MySQL
docker run -itd --name mysql8.0.34 -p 3306:3306 --privileged=true --restart=always -v /Users/xxx/docker/data/mysql8.0.34/data:/var/lib/mysql -v /Users/xxx/docker/data/mysql8.0.34/config/my.cnf:/etc/my.cnf -e MYSQL_ROOT_PASSWORD=root mysql:8.0.34
- 使用连接工具测试MySQL