What it is
Vagrant is a tool for building and managing virtual machine environments in a single workflow. You reach for Vagrant when you need reproducible development environments that are isolated from your host system.
Installation
Linux
sudo apt update
sudo apt install vagrant
# or for Fedora/CentOS/RHEL
sudo dnf install vagrant
# or for Arch Linux
sudo pacman -S vagrant
macOS
Download the .dmg file from the Vagrant website (https://www.vagrantup.com/downloads) and drag the Vagrant application to your Applications folder.
Windows
Download the .msi installer from the Vagrant website (https://www.vagrantup.com/downloads) and run it.
Note: Vagrant requires a virtualization provider like VirtualBox, VMware, or Hyper-V to be installed and configured on your system. VirtualBox is the default and most common choice.
Core Concepts
- Box: A Vagrant "box" is a pre-packaged base image for a virtual machine. It’s like a template that Vagrant uses to create new VMs. Boxes can be downloaded from the Vagrant Cloud or created by users.
- Vagrantfile: This is a Ruby file that defines your Vagrant environment. It specifies the box to use, network configurations, shared folders, provisioning steps, and more.
- Provider: The underlying virtualization software (e.g., VirtualBox, VMware, Hyper-V) that Vagrant uses to run the virtual machine.
- Provisioning: The process of automatically installing software, configuring services, and setting up the guest machine after it’s created. Vagrant supports shell scripts, Ansible, Chef, Puppet, and more for provisioning.
- Guest Machine: The actual virtual machine running the operating system defined by the box.
Commands / Usage
Environment Initialization
-
vagrant init <box_name>Initializes a new Vagrant environment in the current directory. It creates aVagrantfileusing the specified base box.vagrant init ubuntu/focal64Creates a
Vagrantfileconfigured to use theubuntu/focal64box from Vagrant Cloud. -
vagrant init <box_name> -mInitializes a new Vagrant environment with a minimalVagrantfile.vagrant init generic/ubuntu2004 --minimalCreates a
Vagrantfilewith only the essential configuration.
Machine Management
-
vagrant upStarts and provisions the Vagrant environment. If the machine doesn’t exist, it will be created.vagrant upStarts the VM defined in the current directory’s
Vagrantfile. -
vagrant up <machine-name>Starts a specific machine in a multi-machine environment.vagrant up webserverStarts only the machine named
webserver. -
vagrant haltShuts down the Vagrant machine gracefully.vagrant haltShuts down the VM.
-
vagrant suspendSaves the current state of the machine to disk, allowing for a very fast resume.vagrant suspendSuspends the VM, saving its current state.
-
vagrant resumeRestores a suspended machine to its previous state.vagrant resumeResumes a suspended VM.
-
vagrant reloadReboots the Vagrant machine. If theVagrantfilehas changed, it will reload the configuration and re-provision.vagrant reloadReboots the VM and reloads the configuration.
-
vagrant reload --provisionReboots the Vagrant machine and forces re-provisioning.vagrant reload --provisionReboots the VM and runs all provisioners again.
-
vagrant destroyStops and deletes the Vagrant machine, removing all associated files.vagrant destroyStops and removes the VM.
-
vagrant destroy -fStops and deletes the Vagrant machine without prompting for confirmation.vagrant destroy -fForcefully stops and removes the VM.
-
vagrant statusShows the current status of the Vagrant machines.vagrant statusDisplays the current state (running, stopped, etc.) of the VM.
-
vagrant global-statusShows the status of all Vagrant environments on your system.vagrant global-statusLists all Vagrant projects and their statuses.
SSH and Access
-
vagrant sshConnects to the Vagrant machine via SSH.vagrant sshOpens an SSH session to the VM.
-
vagrant ssh -c "command"Executes a command on the Vagrant machine via SSH without opening an interactive session.vagrant ssh -c "sudo apt update && sudo apt install -y nginx"Updates package lists and installs Nginx on the VM.
-
vagrant ssh-configOutputs SSH configuration details for connecting to the machine.vagrant ssh-configPrints host, port, user, and identity file for SSH connection.
Box Management
-
vagrant box listLists all the Vagrant boxes currently installed on your system.vagrant box listShows all downloaded Vagrant base images.
-
vagrant box add <box_name> <box_url>Adds a new Vagrant box to your local machine.vagrant box add ubuntu/focal64 https://app.vagrantup.com/ubuntu/focal64/0/virtualbox.boxDownloads and adds the specified Ubuntu 20.04 box for VirtualBox.
-
vagrant box remove <box_name>Removes a Vagrant box from your local machine.vagrant box remove ubuntu/focal64Removes the
ubuntu/focal64box. -
vagrant box updateChecks for updates for all installed boxes.vagrant box updateChecks for newer versions of your installed Vagrant boxes.
Provisioning
-
vagrant provisionRuns the provisioners defined in theVagrantfileon an already running machine.vagrant provisionExecutes the provisioning steps defined in the
Vagrantfile. -
vagrant provision --provision-with <provisioner_name>Runs only a specific provisioner (e.g.,shell,ansible).vagrant provision --provision-with shellRuns only the shell provisioners.
Plugins
-
vagrant plugin listLists all installed Vagrant plugins.vagrant plugin listShows currently installed Vagrant plugins.
-
vagrant plugin install <plugin_name>Installs a new Vagrant plugin.vagrant plugin install vagrant-vbguestInstalls the
vagrant-vbguestplugin, which helps keep VirtualBox Guest Additions up-to-date. -
vagrant plugin uninstall <plugin_name>Uninstalls a Vagrant plugin.vagrant plugin uninstall vagrant-vbguestUninstalls the
vagrant-vbguestplugin.
Networking
vagrant portLists the port forwarding information for the Vagrant machine.
Shows which host ports are forwarded to which guest ports.vagrant port
Multi-Machine Environments
-
vagrant up <machine-name>Starts a specific machine in a multi-machine environment.vagrant up databaseStarts only the
databasemachine. -
vagrant ssh <machine-name>Connects to a specific machine in a multi-machine environment.vagrant ssh webserverOpens an SSH session to the
webservermachine. -
vagrant halt <machine-name>Shuts down a specific machine in a multi-machine environment.vagrant halt app_serverShuts down the
app_servermachine. -
vagrant destroy <machine-name>Stops and deletes a specific machine in a multi-machine environment.vagrant destroy worker_node -fForcefully destroys the
worker_nodemachine.
Common Patterns
-
Setting up a web server with Nginx: Create a
Vagrantfilewith a basic Ubuntu box and add a shell provisioner to install and configure Nginx.# Vagrantfile Vagrant.configure("2") do |config| config.vm.box = "ubuntu/focal64" config.vm.network "forwarded_port", guest: 80, host: 8080 config.vm.provision "shell", inline: <<-SHELL sudo apt update sudo apt install -y nginx sudo systemctl start nginx sudo systemctl enable nginx SHELL endThen run:
vagrant upAccess Nginx at
http://localhost:8080. -
Sharing your project directory: By default, Vagrant shares your project directory (where the
Vagrantfileis) to/vagrantinside the guest machine. You can customize this.# Vagrantfile Vagrant.configure("2") do |config| config.vm.box = "ubuntu/focal64" config.vm.synced_folder "./app", "/var/www/html" endThis shares the local
./appdirectory to/var/www/htmlon the guest. -
Using multiple machines: Define multiple VMs in a single
Vagrantfile.# Vagrantfile Vagrant.configure("2") do |config| config.vm.define "web" do |web| web.vm.box = "ubuntu/focal64" web.vm.network "private_network", ip: "192.168.33.10" end config.vm.define "db" do |db| db.vm.box = "ubuntu/focal64" db.vm.network "private_network", ip: "192.168.33.11" end endThen manage them individually:
vagrant up web vagrant ssh db vagrant halt web -
Running a Docker container on a Vagrant VM: Provision a Vagrant VM to install Docker and run a container.
# Vagrantfile Vagrant.configure("2") do |config| config.vm.box = "ubuntu/focal64" config.vm.network "forwarded_port", guest: 80, host: 8080 config.vm.provision "shell", inline: <<-SHELL sudo apt update sudo apt install -y apt-transport-https ca-certificates curl software-properties-common curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add - sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu focal stable" sudo apt update sudo apt install -y docker-ce sudo usermod -aG docker vagrant # Add vagrant user to docker group SHELL endAfter
vagrant up, SSH into the VM and run Docker commands:vagrant ssh sudo docker run -d -p 80:80 nginx exitAccess Nginx at
http://localhost:8080. -
Using Vagrant Cloud for boxes: Search for boxes on https://app.vagrantup.com/boxes/search and use their names (e.g.,
hashicorp/bionic64,centos/7).vagrant init hashicorp/bionic64 vagrant up
Gotchas
- Provider Compatibility: Ensure the box you download is compatible with your installed virtualization provider (VirtualBox, VMware, etc.). Boxes are often specific to a provider.
- Synced Folder Performance: Default synced folders (especially on macOS and Windows) can be slow due to filesystem synchronization overhead. Consider using NFS for Linux guests or
synced_folderoptions likersyncfor better performance. - Guest Additions/VMware Tools: For optimal performance and features (like seamless mouse integration, shared clipboard, better resolution), ensure the appropriate guest additions (VirtualBox) or VMware Tools are installed and up-to-date on the guest. The
vagrant-vbguestplugin helps with this for VirtualBox. - Port Conflicts: If you try to forward a host port that is already in use,
vagrant upwill fail. Checkvagrant portto see existing forwards and choose available host ports. VagrantfileSyntax: TheVagrantfileis a Ruby file. Syntax errors will prevent Vagrant from starting your environment.vagrant destroyis Permanent:vagrant destroyremoves the VM and all its data. If you need to preserve data, ensure it’s in a synced folder or managed externally.- Provisioner Idempotency: Ensure your provisioners are idempotent – meaning running them multiple times has the same effect as running them once. This is crucial for
vagrant reload --provisionandvagrant provision. - Network Configuration: Be mindful of the network types (
private_network,public_network,forwarded_port).private_networkcreates a host-only network, useful for host-guest communication without exposing the VM to the external network.forwarded_portmaps a port on the host to a port on the guest.