DEV Community

Cover image for Exploring Vagrant: Port Forwarding - Part 4
Syam SV
Syam SV

Posted on

Exploring Vagrant: Port Forwarding - Part 4

Port forwarding in Vagrant allows you to expose ports from your virtual machine (VM) to your host machine, making services running inside the VM accessible from the host or even from other devices on the network. This is particularly useful when you're running applications inside a VM and want to interact with them from your host machine's web browser or other tools.

By default port 22 (ssh) of the guest vm is mapped to port 2222 of the host machine

To set up port forwarding in Vagrant is simple and the following

Vagrant.configure("2") do |config| 
    #  other configuration settings 
    config.vm.network "forwarded_port", guest: <guest_port>, host: <host_port> end
Enter fullscreen mode Exit fullscreen mode

Example:

Vagrant.configure("2") do |config|
  config.vm.box = "ubuntu/jammy64"
  config.vm.provider "virtualbox" do |vb|
    vb.memory = 2048
    vb.cpus = 2
  end 
  config.vm.provision :ansible do|ansible| 
    ansible.playbook = "playbook.yml"
  end 

  config.vm.network "forwarded_port", guest: 80, host: 8080 ,auto_correct: true 
end
Enter fullscreen mode Exit fullscreen mode

autocorrect: true part will relocate the port forwarding to other port if the host port is busy

After making the changes to your Vagrantfile, save the file and run the following commands in the directory where your Vagrantfile is located:

vagrant up 
Enter fullscreen mode Exit fullscreen mode

or if your vm is already running

vagrant reload --provision
Enter fullscreen mode Exit fullscreen mode

With the port forwarding set up, you can now access the service running inside the VM using the host machine's IP address and the host port you specified. For the example above, you would access the service in a web browser at http://localhost:8080

Multi port forwarding

To forward multiple ports in Vagrant, you can simply add multiple config.vm.network "forwarded_port" entries in your Vagrantfile. Each entry will define the port forwarding for a specific service running inside the VM. Here's how you can do it:

Vagrant.configure("2") do |config|
  config.vm.box = "ubuntu/jammy64"

  config.vm.network "forwarded_port", guest: 80, host: 8080
  config.vm.network "forwarded_port", guest: 443, host: 8443
  config.vm.network "forwarded_port", guest: 3306, host: 3306
end

Enter fullscreen mode Exit fullscreen mode

In the example above, three ports are being forwarded: port 80 on the guest VM to port 8080 on the host, port 443 on the guest VM to port 8443 on the host, and port 3306 on the guest VM to port 3306 on the host.

Top comments (0)