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 thread1,discussion 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:3306and then connect to the ip of the Docker VM on port3306
獲取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:

