localhost访问容器mysql失败,从Docker容器连接到localhost上的MySQL

I have mysql running on my localhost

I can connect it by running:

mysql -h 127.0.0.1 -P 3306 -u root -p

I also ran docker container with command:

docker run -tid -v $(pwd):/code -p 3306:3306 -p 5000:5000 --name container container

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

But it gives me error:

ERROR 2003 (HY000): Can't connect to MySQL server on '127.0.0.1' (111)

What am I doing wrong? Ports seems to be correct.

EDIT 1

Output 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)

解决方案

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

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值