Networking (Port Forwarding)
In order to access the Vagrant environment created, Vagrant exposes some high-level networking options for things such as forwarded ports, connecting to a public network, or creating a private network. The high-level networking is meant to define an abstraction that works across multiple providers such as VirtualBox, VMWare, etc.
In the previous chapter (Provisioning), we have a web server up and running with the ability to modify files from our host and have them automatically synced to the guest. However, accessing the web pages simply from the terminal from inside the machine is not very satisfying. In this chapter, we'll use Vagrant's networking features to give us additional options for accessing the virtual machine from our host machine.
Port forwarding allows us to specify ports on the guest machine to share via a port on the host machine. This allows us to access a port on our host machine, but actually have all the network traffic forwarded to a specific port on the guest machine, over either TCP or UDP.
Let's setup a port forwarding so that we can access Apache in our guest by configuring Vagrantfile:
Vagrant.configure(VAGRANTFILE_API_VERSION) do |config| config.vm.box = "ubuntu/trusty32" config.vm.provision :shell, path: "bootstrap.sh" config.vm.network :forwarded_port, host: 4567, guest: 80 end
Our guest machine is running a web server listening on port 80. The configuration makes a forwarded port mapping to port 4567 on our host machine. We can then open our browser to localhost:4567 and browse the website, while all actual network data is being sent to the guest. In short, this will allow accessing port 80 on the guest via port 4567 on the host.
Run a vagrant reload:
k@laptop:~/my_vagrant$ vagrant reload --provision ... ==> default: Preparing network interfaces based on configuration... default: Adapter 1: nat ==> default: Forwarding ports... default: 80 => 4567 (adapter 1) ...
Once our virtual machine is up and running again, we can see a web page that is being served from the virtual machine that was automatically setup by Vagrant. Type in http://127.0.0.1:4567 in our browser:
Ph.D. / Golden Gate Ave, San Francisco / Seoul National Univ / Carnegie Mellon / UC Berkeley / DevOps / Deep Learning / Visualization