问题描述
我在本地主机上运行mysql我可以通过运行它来连接它:
I have mysql running on my localhostI can connect it by running:
mysql -h 127.0.0.1 -P 3306 -u root -p
我还使用以下命令运行了Docker容器:
I also ran docker container with command:
docker run -tid -v $(pwd):/code -p 3306:3306 -p 5000:5000 --name container container
我想从docker容器访问Mysql数据库.所以我也从docker容器中输入:
And I want to access my Mysql db from docker container. So I also type from docker container:
mysql -h 127.0.0.1 -P 3306 -u root -p
但这给了我错误:
ERROR 2003 (HY000): Can't connect to MySQL server on '127.0.0.1' (111)
我做错了什么?端口似乎是正确的.修改1 ifconfig
在docker中的输出:
What am I doing wrong? Ports seems to be correct.EDIT 1Output of ifconfig
in docker:
eth0 Link encap:Ethernet HWaddr 02:42:ac:11:00:02
inet addr:172.17.0.2 Bcast:0.0.0.0 Mask:255.255.0.0
inet6 addr: fe80::42:acff:fe11:2/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:1780 errors:0 dropped:0 overruns:0 frame:0
TX packets:977 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:2225781 (2.2 MB) TX bytes:56572 (56.5 KB)
lo Link encap:Local Loopback
inet addr:127.0.0.1 Mask:255.0.0.0
inet6 addr: ::1/128 Scope:Host
UP LOOPBACK RUNNING MTU:65536 Metric:1
RX packets:28 errors:0 dropped:0 overruns:0 frame:0
TX packets:28 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1
RX bytes:1400 (1.4 KB) TX bytes:1400 (1.4 KB)
推荐答案
即使您将MySQL配置为侦听所有接口,然后从您的容器通过非环回IP访问MySQL,您仍可能会发现Docker的路由,NAT ,并且防火墙规则不允许您访问主机上运行的服务.快速的解决方法是使用以下命令在主机网络堆栈上运行容器:
Even if you configure MySQL to listen on all interfaces, and then from your container access MySQL from a non-loopback IP, you may find that Docker’s routing, NAT, and firewall rules do not allow you to access services running on the host. The fast workaround for this is to run your container on the host network stack with:
docker run -tid -v $(pwd):/code -p 3306:3306 -p 5000:5000 \
--name container --net host container
您还可以将MySQL移到在同一Docker网络上运行的容器中,然后使用Docker的DNS服务发现通过容器名称访问它.
You can also also move MySQL inside a container running on the same Docker network, and then access it via the container name using Docker’s DNS service discovery.
这篇关于从Docker容器连接到localhost上的MySQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!