Chapter 4. Vagrantfile

Table of Contents

4.1. Port forwarding

Vagrantfile is a configuration file. It was created when you issued the command vagrant init. It’s written in the Ruby language, so it' s very easy to read. There are a lot of defaults that are already defined in this config file. You simply need to uncomment them if you need to enable any particular functionality e.g. port forwarding etc. The Vagrantfile has a simple structure, everything is inside the Vagrant configure block. See the code example below

Example 4.1. Vagrantfile

Vagrant configure(2) do |config|
   # various configurations
end

4.1. Port forwarding

Vagrant boxes are kind of insecure out of the box. That’s why the public_network setting is commented by default. Think of it this way, a computer on a private network is usually behind a firewall and/or a router. Most computers on an office setting belong to this category. Your office workstation is not reachable from the internet because because it is behind a router.

When you create a vagrant project, the vm is on a private network. That means you cannot reach any of its ports from the host machine, unless you define a public network. Having a vm that is not accessible from your host machine is not very useful, so we need a way to reach the applications running on the vm. One way to do it via port forwarding. Basically, we will map a port number on the host machine to a port of on the guest machine (your vm). That way, when we try to communicate to a port on the host machine, that request will be forwarded to the port of the guest machine, thus making the services of the guest machine reachable.

Example 4.2. port forwarding configuration

config.vm.network "forwarded_port", guest:80,  host:8080, id: "whatever" 123

1

guest:80. The vm will listen on port 80, this is usually a web server like Apache or NGinx or any other webserver that you want to use

2

host:8080. This is the port on the host machine (your actual PC where the vagrant is installed). When you launch a browser and go to http://localhost:8080, you are actually hitting the port 80 of your vm

3

id: whatever. This is optional, but it is always a good idea to to put an id on your port mapping definition

You can forward more than one port. If you need to open more ports on the guest machine, just define each mapping on its line

Example 4.3. forwarding more than one port

config.vm.network "forwarded_port", guest:80,  host:8080, id: "apache"
config.vm.network "forwarded_port", guest:4000,  host:3000, id: "node"