阿里云-云小站(无限量代金券发放中)
【腾讯云】云服务器、云数据库、COS、CDN、短信等热卖云产品特惠抢购

Docker创建MySQL镜像并成功进行远程连接

155次阅读
没有评论

共计 2089 个字符,预计需要花费 6 分钟才能阅读完成。

1. 安装

1.1 拉取镜像

docker pull MySQL

拉取成功可以验证一下

docker images

1.2 创建并启动一个 mysql 容器

docker run --name ly-mysql -e MYSQL_ROOT_PASSWORD=123456 -p 3306:3306 -d mysql
  • –name:给新创建的容器命名,此处命名为 ly-mysql
  • -e:配置信息,此处配置 mysql 的 root 用户的登陆密码
  • -p:端口映射,此处映射主机 3306 端口到容器 pwc-mysql 的 3306 端口
  • -d:成功启动容器后输出容器的完整 ID.
  • 最后一个 mysql 指的是 mysql 镜像名字

到这里我们查看容器运行状态:

$ sudo docker ps

可以看到容器的简写 ID,容器的源镜像,创建时间,状态,端口映射信息,容器名字等。

1.3 连接测试

使用 navicat 远程连接,这里碰到几个问题

1.3.1 mysql 连接 IP 问题

首先这个 IP 肯定不是 localhost,然后以为是 mysql 容器的 IP

1.3.1.1 查看 mysql 容器的 ip
docker inspect --format '{{.NetworkSettings.IPAddress}}' <container-ID> 

结果是:172.17.0.2
但是还是连接不上

1.3.1.2 获取 docker 主机 IP
docker-machine ip

192.168.99.100

这个可以连接

结论:

当使用 windows 和 macOS 时,不应该使用 localhost 而应该使用 docker-machine ip

1.3.2 连接 mysql 8 提示 2059 – authentication plugin ‘caching_sha2_password…

原因:由于 myslq8 不支持动态修改密码验证方式
解决方案:

  1. 进入 mysql 容器
docker exec -it ly-mysql bash
  1. 连接 mysql
mysql -uroot -p

3. 修改配置

use mysql;
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'new password';
FLUSH PRIVILEGES;

1.4 其他

1.4.1 记录几个命令

1.4.1.1 退出容器
  1. 如果要正常退出不关闭容器,请按 Ctrl+P+ Q 进行退出容器
  2. 如果使用 exit 退出,那么在退出之后会关闭容器,可以使用下面的流程进行恢复
  • 使用 docker restart 命令重启容器
  • 使用 docker attach 命令进入容器 
    1.4.1.2 修改 MySQL 配置文件有两种方法:
  • 一是进入容器,修改容器里的 MySQL 的配置文件,然后重新启动容器,例如:
$ sudo docker exec -it ly-mysql /usr/bin/bash

然后可以进入容器的命令行模式,接着修改 /etc/mysql/my.cnf 文件即可

  • 二是挂载主机的 mysql 配置文件,官方文档如下:
    The MySQL startup configuration is specified in the file /etc/mysql/my.cnf, and that file in turn includes any files found in the /etc/mysql/conf.d directory that end with .cnf. Settings in files in this directory will augment and/or override settings in /etc/mysql/my.cnf. If you want to use a customized MySQL configuration, you can create your alternative configuration file in a directory on the host machine and then mount that directory location as /etc/mysql/conf.d inside the mysql container.

If /my/custom/config-file.cnf is the path and name of your custom configuration file, you can start your mysql container like this (note that only the directory path of the custom config file is used in this command):

$ docker run --name some-mysql -v /my/custom:/etc/mysql/conf.d -e MYSQL_ROOT_PASSWORD=my-secret-pw -d mysql:tag

This will start a new container some-mysql where the MySQL instance uses the combined startup settings from /etc/mysql/my.cnf and /etc/mysql/conf.d/config-file.cnf, with settings from the latter taking precedence.

正文完
星哥说事-微信公众号
post-qrcode
 0
星锅
版权声明:本站原创文章,由 星锅 于2022-01-22发表,共计2089字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
【腾讯云】推广者专属福利,新客户无门槛领取总价值高达2860元代金券,每种代金券限量500张,先到先得。
阿里云-最新活动爆款每日限量供应
评论(没有评论)
验证码
【腾讯云】云服务器、云数据库、COS、CDN、短信等云产品特惠热卖中