21

Is there a way to forward a range of ports using vagrant 1.2.1 or higher? I know that you can forward any number of ports individually by using

config.vm.forward_port 80, 4567

Or, is the answer simply don't use vagrant to do such a thing?

3
  • Does this help? docs.vagrantup.com/v2/networking/forwarded_ports.html
    – dawud
    Jun 29, 2013 at 10:44
  • Not exactly. Wanted to know if you can specify a range of ports to be open, rather than one at a time. Perhaps I'll contact the author directly.
    – Acorn
    Jun 30, 2013 at 12:19
  • 5
    Since the Vagrantfile is just a Ruby script you might be able to write a for loop that executes config.vm.forward_port for every port you want. I'm not fluent in Ruby, so I can't really help you with code.
    – Lasar
    Jul 8, 2013 at 12:27

2 Answers 2

30

If anyone needs an example of how to do the loop in your Vagrantfile here it is:

for i in 64000..65535
    config.vm.network :forwarded_port, guest: i, host: i
end

The above loop will forward all ports between 64000 and 65535 to the exact same port on the guest (note that 64000 and 65535 are inclusive).

7
  • 2
    On my computer vagrant was a bit long to map 1000 ports. Unless you really need so many mapped ports, you should map 50 ports.
    – Antoine
    Aug 26, 2015 at 12:17
  • @Antoine yes I've noticed that it is very slow as well. I normally end up just using 10 to 20 for development boxes. Sep 17, 2015 at 2:17
  • Extremely slow to check used ports on windows, errors out once the command line limitation kicks in. Mar 2, 2018 at 11:25
  • @AlexanderT how many ports are you trying to forward? Mar 2, 2018 at 16:13
  • @ddelrio1986 around a thousand. Mar 3, 2018 at 13:28
2

The 'for' examples above are correct for doing an inclusive range. If you would like to forward a set of specific ports, you need to use the Ruby .each operator.

The variables can go inside or outside of the main Vagrant.configure loop.

UDP_PORTS_LIST={
  "5000" => 5000, # Some service
}

TCP_PORTS_LIST={
  "5900" => 5900, # VNC
}

The loops need to go inside the Vagrant.configure block for the VM you want to map them for (remember you can have multiple VMs in a single Vagrantfile).

UDP_PORTS_LIST.each do |guest, host|
  config.vm.network "forwarded_port", guest: "#{guest}", host: "#{host}", protocol: "udp"
end
TCP_PORTS_LIST.each do |guest, host|
  config.vm.network "forwarded_port", guest: "#{guest}", host: "#{host}", protocol: "tcp"
end

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.