連接docker里的mysql


Background: 之前我解決了如何在docker創建mysql並用docker-compose up啟動的問題。然后我試圖用我寫的spring boot項目來訪問mysql數據庫

 

Problem:java無法連接mysql,經檢查,不是java的問題--因為我安裝了mysqlworkbench也無法連接mysql。下面是docker ps的結果:

 ~ docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                    NAMES
0aaa6dbcc7bb        mysql               "docker-entrypoint..."   10 hours ago        Up About an hour    0.0.0.0:3306->3306/tcp   runninginformationanalysisservice_mysql_1

使用mysql workbench連接時使用的hostname是localhost或者127.0.0.1,均無法連接。

 

 

Solution

問題出在host ip上,

當使用windows和macOS時,不應該使用localhost而應該使用docker-machine ip(discussion thread1discussion thread2 ) 

If you are on Windows or OSX using docker-machine/boot2docker, you won't be able to connect directly to a container's IP address from the host. You would need to start the container with -p 3306:3306 and then connect to the ip of the Docker VM on port 3306

獲取docker主機 IP

docker-machine ip
192.168.99.100

獲取 docker container ip:---注意,並不能直接訪問container。

docker inspect --format '{{ .NetworkSettings.IPAddress }}' runninginformationanalysisservice_mysql_1
172.17.0.2

當使用docker-machine ip作為hostname后,成功連接了mysql:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM