Vagrant is software for managing virtual machines on your computer. You can use these virtual machines to run applications in their own self-contained environment, with their own operating system and other dependencies running.
A Vagrant box is configured by a Vagrantfile found in the project root. This project root folder is shared (or ‘synced’) between your computer (the “host” machine) and the virtual environment (or “guest” machine).
Select which base Vagrant box to build on top of, like this:
config.vm.box = "ubuntu-14"
Sync additional folders like this:
config.vm.synced_folder "~/Sites/vagrant-shared", "/home/vagrant-shared"
On some of our projects, we sync ~/vagrant-shared. A synced folder is required; the box will not boot up without it being found.
Map the guest machine to an ip on the host machine like this:
config.vm.network "private_network", ip: "188.8.131.52"
Ports on the guest machine can be mapped to ports on the host machine. Best practice is to disable MySQL on the host machine, then map the guest port 3306 to host port 3306, like this:
config.vm.network "forwarded_port", guest: 3306, host: 3306
Set up a single hostname on the guest machine like this:
config.vm.provision "shell", inline: "sudo hostname dirdev.reverehq.com"
Set your guest machine to launch Apache in the background like this:
config.vm.provision "shell", inline: "sudo service apache2 restart", run: "always"
When a guest box gets created (aka “provisioned”), it can run a sequence of startup scripts to install dependencies and do other setup activity. Add startup scripts like this:
config.vm.provision "shell", privileged: true, path: "vm/system.sh" config.vm.provision "shell", privileged: true, path: "vm/app.sh"
As a best practice, separate system-level actions from app-specific actions.
To include dotfiles or other shell customizations, put a .bash_profile file in your shared vagrant-shared directory, and add this to your app.sh setup script (or equivalent):
ln -s /home/vagrant-shared/.bash_profile /home/vagrant/.bash_profile
Some bash features are not available (such as including external files). See an example profile here.
- Install Vagrant
- Install VirtualBox
Installing a Vagrant Box
Navigate to your project directory, and start your guest box like this:
(If it has not been provisioned, it will be provisioned.)
Then you can SSH into the box like this:
You can stop a vagrant box like this:
Halting will free up any ports the box was using. Later you can vagrant up again to re-start the box without re-provisioning.
Update a base box like this:
vagrant box update
Completely destroy a box like this: