Search code examples
vagrantportforwarding

How can Vagrant forward multiple ports on the same machine?


I'm wondering how to setup a Vagrant file that will put up a machine with two ports forwarded. This is my current Vagrantfile, which is forwarding the 8080 page:

Vagrant.configure("2") do |config|

  config.vm.box = "precise32"
  config.vm.box_url = "http://files.vagrantup.com/precise32.box"
  config.vm.provider "virtualbox"

  config.vm.network :forwarded_port, guest: 8080, host: 8080
  config.vm.provision :shell, :path => "start.sh", :args => "'/vagrant'"

  config.vm.network :public_network
end

Thanks!


Solution

  • If you want to forward two ports, you may simply add another line like this:

    config.vm.network :forwarded_port, guest: 8080, host: 8080
    config.vm.network :forwarded_port, guest: 5432, host: 5432
    

    A better way, in my opinion, is to setup a private network (or host-only network), so that you don't have to forward all the ports manually.

    See my post here: Vagrant reverse port forwarding?

    Additional tips

    If you use the :id feature when defining :forward_port entries you need to make sure that each is unique. Otherwise they'll clobber each other, and the last one defined will typically win out.

    For example:

    config.vm.network "forwarded_port", guest: 8080, host: 8080, id: 'was_appserver_http'
    config.vm.network "forwarded_port", guest: 9043, host: 9043, id: 'ibm_console_http'
    config.vm.network "forwarded_port", guest: 9060, host: 9060, id: 'ibm_console_https'