February 05, 2015

Up and Running with Vagrant

Learn how to get started using Vagrant for local development, and learn more about servers!

Learn how to get started using Vagrant for local development, and learn more about servers!Download and install both Virtualbox and Vagrant - these both contain easy to use installation wizards and don't require configuration after installation.

For Vagrant, we'll use Ubuntu 14.04 LTS servers, which are available on Atlas (formerly Vagrant Cloud for use with Vagrant.

Once installed:

mkdir ~/Sites/vagrant
cd ~/Sites/vagrant

# Create a Vagrantfile which will use Ubuntu 14.04
vagrant init ubuntu/trusty64

Edit the Vagrantfile:

# -*- mode: ruby -*-
# vi: set ft=ruby :

# Many comments ommitted for brevity

VAGRANTFILE_API_VERSION = "2"
Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|

  # Every Vagrant virtual environment requires a box to build off of.
  config.vm.box = "ubuntu/trusty64"
end

We won't change anything yet. Exit the file and we can start a virtual machine:

# Download the Ubuntu server if not already downloaded and start the server
vagrant up

Once that's up and running, we can SSH into the server:

vagrant ssh

# See shared directory
cd /vagrant
touch hello.txt

# edit hello.txt
vim hello.txt
> Hello!

Then we can see that the files are indeed shared and editable within server and host.

Let's see the setting for shared directories within the Vagrantfile:

# -*- mode: ruby -*-
# vi: set ft=ruby :

# Many comments ommitted for brevity

VAGRANTFILE_API_VERSION = "2"
Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|

  # Every Vagrant virtual environment requires a box to build off of.
  config.vm.box = "ubuntu/trusty64"

  # Default shared folder setting
  config.vm.synced_folder ".", "/vagrant"
end

You can change this as you'd need or like.

Lastly, let's see forwarding a port:

# -*- mode: ruby -*-
# vi: set ft=ruby :

# Many comments ommitted for brevity

VAGRANTFILE_API_VERSION = "2"
Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|

  # Every Vagrant virtual environment requires a box to build off of.
  config.vm.box = "ubuntu/trusty64"

  # Default shared folder setting
  config.vm.synced_folder ".", "/vagrant"

  # Forward host's port 8080 to server's port 80
  config.vm.network "forwarded_port", guest: 80, host: 8080
end

After saving these changes to the Vagrantfile, reload the virtual machine so these settings take affect:

vagrant reload

Then test out the forwarded port. Start a simple webserver anywhere within the Vagrant virtual machine:

# Log into the server
vagrant ssh

# Start a simple HTTP server provided by Python out of the box
sudo python -m SimpleHTTPServer 80

Then go into your browser and head to localhost:8080. This hsoudl show the web server being hosted by your web server! It's forwarding HTTP requests to port 8080 on your server's port 80 (which has the Python HTTP server listening).

All Topics