Port-forwarding

A powerful yet simple way to configure networking in Vagrant is to use port-forwarding. This does not require any advanced knowledge or configuration on your part.

Port-forwarding is the action of linking a port on your host machine to a port on the guest machine. It is as simple as that, but can be really powerful as it allows you to get up and running quickly. 

The following are the steps to configure port-forwarding:

  1. Open up our Vagrantfile. We'll start with a very basic Vagrantfile by using the ubuntu/xenial64 box and a basic shell provision script to install the nginx web server:
  1. Once you've saved the Vagrantfile, run the vagrant up command:
  1. Once the box has completed installing nginx and is up and running, open your web browser and try navigating to localhost:8080:
  1. nginx should be available (possibly not on port 8080), but as you can see, we cannot access it. This is because we have not yet set up port-forwarding. If we access localhost from inside the Vagrant machine, we should be able to access it.
  1. Run the vagrant ssh command. Once in the Vagrant machine, run the curl localhost command. This should return the nginx default page in HTML code:
  1. Let's set up port forwarding so we can access this page from the host machine (outside Vagrant).
  1. Exit out of the machine and open up your Vagrantfile again. In the following code (you can see it on line 8 of the following screenshot)  config.vm.network "forwarded_port", guest: 80, host: 8080:

Let's break down the line that we just added into the Vagrantfile. First of all, we are calling the config.vm.network namespace to tell Vagrant that we want to change the network settings. The first argument we are passing in is forwarded_port, followed by two different port numbers. The first port is the port number that we will be accessing inside the guest/Vagrant machine. In the preceding example, we will be accessing port 80, which is generally the default port for a website/web server. The final argument is the host port, which is the port that we connect to from our host. In our example, it would be 8080, and via URL we could access it at http://localhost:8080, which would connect to Vagrant and access the machine's port 80.

  1. Save the Vagranfile and run the vagrant reload --provision command.
  1. This will restart the Vagrant machine and force provisioning to run again. You'll see, at the bottom of the following screenshot, that it now includes our new port in the default: Forwarding ports... section:
  1. Once the Vagrant machine is finished provisioning and is up and running, try to open localhost:8080 in your browser:

You should see the Welcome to nginx! default page. Congratulations! You have successfully configured port-forwarding on your Vagrant box.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.115.195