连接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:

 

posted @ 2017-12-20 02:27  aureole420  阅读(21132)  评论(1)    收藏  举报