What is Vagrant?
Vagrant is an open-source tool for building and managing virtual machine environments in a single workflow. It provides easy-to-configure, reproducible, and portable work environments built on top of industry-standard technology and controlled by a single consistent workflow.
Key Features
- Reproducible Environments: Consistent development environments across teams
- Multi-Provider Support: Works with VirtualBox, VMware, AWS, and more
- Provisioning: Automated setup using shell scripts, Ansible, Chef, or Puppet
- Networking: Flexible networking options for VM communication
- Synced Folders: Share files between host and guest machines
- Multi-Machine: Define and control multiple machines with single Vagrantfile
Vagrantfile Example
# -*- mode: ruby -*-
# vi: set ft=ruby :
Vagrant.configure("2") do |config|
# Base box
config.vm.box = "ubuntu/bionic64"
# Network configuration
config.vm.network "private_network", ip: "192.168.33.10"
config.vm.network "forwarded_port", guest: 80, host: 8080
# Synced folders
config.vm.synced_folder "./src", "/var/www/html"
# Provider-specific configuration
config.vm.provider "virtualbox" do |vb|
vb.memory = "1024"
vb.cpus = 2
end
# Provisioning
config.vm.provision "shell", inline: <<-SHELL
apt-get update
apt-get install -y apache2 php mysql-server
systemctl enable apache2
systemctl start apache2
SHELL
# Multi-machine setup
config.vm.define "web" do |web|
web.vm.box = "ubuntu/bionic64"
web.vm.network "private_network", ip: "192.168.33.11"
end
config.vm.define "db" do |db|
db.vm.box = "ubuntu/bionic64"
db.vm.network "private_network", ip: "192.168.33.12"
end
end
Common Vagrant Commands
# Initialize a new Vagrant environment
vagrant init ubuntu/bionic64
# Start and provision the vagrant environment
vagrant up
# SSH into the running Vagrant machine
vagrant ssh
# Reload the Vagrant machine (restart with new config)
vagrant reload
# Suspend the machine
vagrant suspend
# Resume a suspended machine
vagrant resume
# Stop the running machine
vagrant halt
# Destroy the machine
vagrant destroy
# Check status of machines
vagrant status
# Show global status of all Vagrant environments
vagrant global-status
Benefits of Using Vagrant
- Environment Consistency: Same environment across development, testing, and production
- Easy Onboarding: New team members can get started quickly
- Isolation: Keep development environments separate from host system
- Version Control: Vagrantfile can be version controlled with project code
- Cost Effective: Reduce infrastructure costs for development environments