1. 程式人生 > >Docker建立MySQL映象併成功進行遠端連線

Docker建立MySQL映象併成功進行遠端連線

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.