欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

docker 创建mysql镜像,并成功进行远程连接

程序员文章站 2022-12-16 10:39:32
1.安装 1.1 拉取镜像 拉取成功可以验证一下 1.2 创建并启动一个mysql容器 –name:给新创建的容器命名,此处命名为ly mysql e:配置信息,此处配置mysql的root用户的登陆密码 p:端口映射,此处映射主机3306端口到容器pwc mysql的3306端口 d:成功启动容器 ......

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.