让流浪者/虚拟箱访问主机服务的最简单方法是什么



我已经阅读了很多例子(包括这里的例子以及各种博客和virtualbox/warrant文档(,现在我认为我应该能够做到这一点。

我最终想做的是与主机上的docker守护进程以及我任意启动的所有后续服务进行通信。

为了让它发挥作用,我在主机上运行了一个简单的nginx容器,并确认它可以工作:

$ docker run --name some-nginx -d -p 8080:80 docker.io/library/nginx:1.17.9
$ curl localhost:8080
> Welcome to nginx!

在我的流浪者文件中,我定义了我的主机专用网络:

config.vm.network "private_network", ip: "192.168.50.4",
virtualbox__intnet: true

现在,在我的客人流浪箱里,我希望我能访问同一个端口:

$ curl localhost:8080
> curl: (7) Failed to connect to localhost port 8080: Connection refused
$ curl 127.0.0.1:8080
> curl: (7) Failed to connect to 127.0.0.1 port 8080: Connection refused
$ curl 192.168.50.4:8080 # I hope not, but maybe this will work?
> curl: (7) Failed to connect to 192.168.50.4 port 8080: Connection refused

如果您是;内部";Vagrant客户机,localhost将是该机器的本地环回适配器,而不是您的主机。

在您正在使用的VirtualBox虚拟化中,您可以始终通过10.0.2.2地址连接到主机本地主机上运行的服务。请参阅:https://www.virtualbox.org/manual/ch06.html#network_nat

因此,在您的情况下,web服务器在主机的8080端口上运行,使用

curl 10.0.2.2:8080

意味着成功

  • 运行vagrant up启动vm,并使用NAT作为网络接口,这意味着来宾vm将与同一网络中的主机一样运行。

  • vagrant ssh到vm中,如果您的机器没有工具netstat,请安装网络工具

  • 使用netstat -rn查找任何可路由的网关。在网关10.0.2.2192.168.3.1之下,它们是来宾vm中的网关。

    [vagrant@localhost ~]$ netstat -rn
    Kernel IP routing table
    Destination     Gateway         Genmask         Flags   MSS Window  irtt Iface
    0.0.0.0         10.0.2.2        0.0.0.0         UG        0 0          0 eth0
    0.0.0.0         192.168.3.1     0.0.0.0         UG        0 0          0 eth2
    10.0.2.0        0.0.0.0         255.255.255.0   U         0 0          0 eth0
    192.168.3.0     0.0.0.0         255.255.255.0   U         0 0          0 eth2
    192.168.33.0    0.0.0.0         255.255.255.0   U         0 0          0 eth1
    
  • 转到主机并运行ifconfig。找出主机共享的网关192.168.3.1,主机拥有IP192.168.3.x。并确保主机上的服务可以在192.168.3.x上访问。

  • 并确保主机上的服务可以在192.168.3.x上访问。

    • 在主机curl -v http://<192.168.3.x>:<same port on host>上尝试,如果可以访问,可以
  • 现在转到来宾vm,尝试curl -v http://<192.168.3.x>:<same port on host>。如果可以访问太

  • 现在,您可以从guestvm访问主机上的服务。

最新更新