从docker容器访问宿主机

主要解决从容器内访问外网的服务。
网上文章的很大内容雷同,除了用–net=host这种硬来的可行外,其它的方法都没看的很懂,按自己的思路整理。

用–add-host=host.docker.internal:host-gateway参数解决

docker run -d --add-host=host.docker.internal:host-gateway xyz

xyz 是容器名
–add-host 参数,意思是向xyz的/etc/hosts文件中增加一条解析

如果不想了解更多,只要解决问题,看到这里就可以了。


点击这里查看官方解释

The --add-host flag supports a special host-gateway value that resolves to the internal IP address of the host. This is useful when you want containers to connect to services running on the host machine.
It’s conventional to use host.docker.internal as the hostname referring to host-gateway. Docker Desktop automatically resolves this hostname, see Explore networking features.
The following example shows how the special host-gateway value works. The example runs an HTTP server that serves a file from host to container over the host.docker.internal hostname, which resolves to the host’s internal IP.

意思是说,host.docker.internal和host-gateway是docker约定的写法。host.docker.internal代表容器的ip,host-gateway代表容器的网关,和宿主机ip是绑定的(ip地址不一样)。因为,网关和容器的ip地址不固定,所以在容器内,需要对应ip地址的地方用这两个写法替代,可以减少耦合。

在看下容器内的/etc/hosts文件,

sudo docker exec d1fe131fca0e cat /etc/hosts

127.0.0.1       localhost
::1     localhost ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
172.17.0.1      host.docker.internal   #增加了这行解析,其它都相对固定的原生解析
172.17.0.2      e341ad84d2cc

可以看到增加了一条解析。172.17.0.1就是容器的gateway。

野生写法

docker run -d --add-host=waiwang.com:host-gateway xyz

打印容器的/etc/hosts文件

127.0.0.1       localhost
::1     localhost ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
172.17.0.1      waiwang.com  #增加了这行解析
172.17.0.2      e341ad84d2cc

在容器内,需要访问宿主机的地方,都可以写waiwang.com

还有更野生的写法,
比如宿主机的ip是192.168.100.100。

docker run -d --add-host=waiwang.com:192.168.100.100 xyz

或者容器内都直接写宿主机的ip。
虽然也可以,但宿主机和容器的ip不固定,可能每次运行都要核对ip,可见就太麻烦了!

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值