如何使用端口转发从同一个文件 运行 多个 vagrant box 实例

How to run multiple vagrant box instances from a same file with a port forwarding

我正在尝试使用循环从一个 vagrant 文件启动 2 个盒子。 它正在工作,但直到我尝试向它添加端口转发。 我以前从未使用 Ruby 进行编程,而且我对使用 vagrant 也不是很高级,所以它可能是一些简单明了的东西,但我不明白它是什么。

这里是简化的例子:

  {
    :hostname => "first",
    :ip => "192.168.100.10",
    :box => "minimal/xenial64",
    :ram => 1024,
    :cpu => 2,
    :port => 9080
  },
  {
    :hostname => "second",
    :ip => "192.168.100.11",
    :box => "minimal/xenial64",
    :ram => 2024,
    :cpu => 1,
    :port => 9081
  }
]

Vagrant.configure(2) do |config|
    machines.each do |machine|
        config.vm.define machine[:hostname] do |node|


            # This is working just fine, each machine gats it's own ip, port, ram, memory
            # as they specified in machines array above

            node.vm.box = machine[:box]
            node.vm.hostname = machine[:hostname]
            node.vm.network "private_network", ip: machine[:ip]
            node.vm.provider "virtualbox" do |vb|
                vb.customize ["modifyvm", :id, "--memory", machine[:ram]]
            end


            # But this is not working the same way for some reason,
            # firs machine gets both ports
            config.vm.network :forwarded_port, guest: 80, host: machine[:port]

            #==> first: Forwarding ports...
            #    first: 80 (guest) => 9080 (host) (adapter 1)
            #    first: 80 (guest) => 9081 (host) (adapter 1)

            # And than second machine obviously can start because of:
            # The forwarded port to 9080 is already in use on the host machine.
        end
    end
end

因为我怀疑它是简单明了的东西,所以我使用了

config.vm.network :forwarded_port, guest: 80, host: machine[:port]

而是

node.vm.network :forwarded_port, guest: 80, host: machine[:port]
应该使用

,因为 node 指的是当前关闭。