Forward new port on running vagrant / virtualbox machine

Vagrant is great for starting up virtual machines for development. A quick and easy setup is to use basic networking with port forwarding so you can serve a website or web application on a port and use a browser on the host machine to see the work in progress.

Say you want to serve your site on port 3000, use this in your Vagrantfile:

Vagrant.configure("2") do |config|
    config.vm.network "forwarded_port", guest: 3000, host: 3000
end

Then, after vagrant up and setting up your development environment on the VM to serve your site on port 3000, you can browse to http://localhost:3000 to view it from the host machine.

If, however, you decide you want another project or service on another port, say another site, but this time from port 3001, it can be a pain to add this to your Vagrantfile and do a vagrant reload. Instead, it’s possible to do this with VirtualBox directly (as long as you’re using VirtualBox as your provider).

The VirtualBox docs hint that this is possible. But, the doc linked to does not give an example. Lucky, the command line VBoxManage utility help shows the arguments needed. So to forward a new port from the guest to the host on a running Vagrant / Virtual Box VM run this from the command line (either make sure VBoxManage is in your path or use the full path to the executable)

VBoxManage controlvm "VM name" natpf1 "guestname,tcp,,3001,,3001"

The command options are the same as those to VBoxManage modifyvm "VM name" --natpf1.

To remove a forwarded port if it’s no longer required, you can run:

VBoxManage controlvm "VM name" natpf1 delete guestname

To help you find the VirtualBox name of your VM, to see a list of machines, run:

VBoxManage list vms

You can also see and change VM information including changing the port forwarding settings through the Oracle VM VirtualBox Manager GUI.

If you decide you want this change to be permanent the next time you do vagrant up, don’t forget to add the port forwarding information to your Vagrantfile as well.

Tags: