iTranslated by AI
Getting Started with Vagrant via Official Tutorials: A Comprehensive Translation and Guide
Introduction
This article is a repost by the author from this Qiita article. I will be writing and making revisions on both platforms for a while.
Target Audience
- You have heard of virtual environments but have never actually used one.
- You have a rough understanding of basic terminal commands (cd, ls, mkdir, etc.).
- You want to quickly grasp the basics of VirtualBox/Vagrant and try using them.
- You want to study Linux using a virtual environment.
Content Overview
To help those described above quickly grasp the overview and usage of Vagrant in a short time, I have translated and summarized two official Vagrant documentation articles:
In summarizing these two documents, I have added very detailed supplementary explanations so that (even beginners) can understand the concepts using only this article as much as possible.
In particular, I have added independent chapters to explain concepts/terms you should know when reading the official documentation and how to install VirtualBox and Vagrant as supplementary information.
(If you don't need these, feel free to skip them!)
Note: If there are points where you think "I don't get this! ━(ノдヽ)━", please leave a comment! Also, if you have feedback like "This translation is too liberal! This supplementary explanation is wrong! (`Д´)", please let me know. <(_ _)>
[Preparation 1] Concepts and Terms to Know
Before actually building a virtual environment using VirtualBox and Vagrant in the next chapter, I will explain seven topics/terms that will help your understanding if you know them beforehand.
1. What is Virtualization with VirtualBox?
According to IT Terminology Dictionary / e-Words, VirtualBox is "an open-source virtualization software. It builds a virtual computer (Virtual Machine/VM) as an application running on an operating system (OS), allowing another OS to run on top of it."
Its main feature is the ability to run virtual machines with different OSs on top of a host (underlying) OS such as Mac, Windows, or Linux. In Vagrant, this type of virtualization software (including VirtualBox) is called a Provider.
In the diagram I created above, the virtualization software sits on top of the host OS. This is called "Host OS virtualization." (There are other types like Hypervisor-based virtualization, but we will skip those for now.)
For now, it's fine to understand it as "placing a virtual machine running a different OS on top of an existing OS."
2. What is a Provider?
A Provider is software that provides a virtual environment. Vagrant builds and operates virtual machines on top of this virtual environment. In this article, we will use VirtualBox as the base provider, but others such as VMware Fusion (Workstation), AWS (EC2), and Rackspace can also be added via plugins.
3. What is Provisioning?
Provisioning is the process of installing and configuring software such as web servers (Apache, Nginx), programming languages (PHP, Python, Ruby, etc.), and DBMS (PostgreSQL, MySQL, etc.) on a virtual machine.
Following the official documentation, we will use shell scripts in this guide, but other provisioning tools like Ansible, Chef, and Puppet can also be used.
4. What is a Box file?
A Box file is a base image file used when starting a virtual machine. You can think of it as a template for a virtual machine.
5. What is Vagrant Cloud?
Vagrant Cloud is an official public repository for Box files. Until I read the Qiita article "The Correct Way to Start Vagrant", I used to download from unofficial Box sites like vagrantbox.es. Reading the official Vagrant documentation properly gave me a good reason to switch. Many thanks!
6. What is a Vagrantfile?
A Vagrantfile is a file that describes the construction of a virtual machine (such as the specifications of the virtual machine to be built using Vagrant, the specification of provisioning tools, etc.).
7. What is a Vagrant Command?
A Vagrant command is a command that makes it easy to operate Vagrant on a terminal.
Summary So Far
Virtualization is possible with VirtualBox alone, but by using Vagrant, you can easily set/share virtual environment configuration information in a Vagrantfile and execute it with Vagrant commands, making environment construction extremely easy.
[Preparation 2] Installing VirtualBox and Vagrant
Installing VirtualBox
First, access the Oracle VirtualBox official page.
Click on "Downloads" on the left side and download the version that matches your environment!
Once the installer opens, simply answer affirmatively to everything, and the installation will finish successfully.
Installing Vagrant
Access the Vagrant official page and click the "Download" button!
Select the version for your environment and click the "Download" button!
A .dmg file will be downloaded, so click on it.
Double-click "Vagrant.pkg" to start the installer.
You can just keep clicking "Continue."
This completes the installation of VirtualBox and Vagrant!
In the next section, we will finally start diving into the official documentation!
[Official] Introduction to Vagrant
What is Vagrant?
Vagrant is a tool for building and managing virtual machine environments in a single workflow.
With a focus on an easy-to-use workflow and automation, Vagrant lowers development environment setup time and increases production parity.
Why Vagrant?
Vagrant provides easy-to-configure, reproducible, and portable work environments (accessible to everyone on the team).
These environments are built on top of industry-standard technology and controlled by a single consistent workflow to help maximize the productivity and flexibility of your team.
Vagrant stands on the shoulders of giants to achieve its power.
Virtual machines are provisioned on top of VirtualBox, VMware, AWS, or any other provider. Industry-standard provisioning tools such as shell scripts, Chef, or Puppet can be used to automatically install and configure software on the virtual machine.
For Developers
Vagrant isolates dependencies and a series of configurations in a single, consistent, disposable environment. Furthermore, it does not mean you will lose access to the tools you are already used to (such as your editor, browser, debugger, etc.).
Once someone (including you) creates a single Vagrantfile, simply running the command vagrant up will install and configure everything needed for your work.
Since other team members create their development environments from the same configuration, regardless of whether they are working on Linux, Mac, or Windows, every team member will be running code on an identical environment with the same dependencies and configurations.
You can say goodbye to the "it only works on my machine" phenomenon (bugs)!
For Operators/DevOps
Vagrant provides disposable environments and a consistent workflow for developing and testing infrastructure management scripts.
You can immediately test shell scripts, Chef cookbooks, Puppet modules, and other things used for local virtual environments like VirtualBox or VMware.
Then, you can test these scripts in remote cloud environments (such as AWS or RackSpace) using the same configuration and following the same flow.
Throw away custom scripts for recycling (AWS) EC2 instances, stop juggling SSH prompts for various machines, and use Vagrant to bring sanity back into your life instead!
For Designers
Vagrant automatically handles all the configuration necessary for web applications, so you can focus solely on your design work!
Once a developer sets up Vagrant, you never have to worry about how to get the app running again.
There is no longer a need to have other developers help fix your environment for design testing. Designers just need to check out the code, run vagrant up, and start designing!
For Everyone
Vagrant is software designed to create virtual environments in the easiest and fastest way possible!
In the next chapter, we will finally enter the Vagrant Quick Start Guide!
[Official] Getting started
1. Quick Start
Prerequisites
- Vagrant is installed
- VirtualBox is installed
Starting an Ubuntu 18.04 LTS 64-bit virtual machine on VirtualBox
The author has already created the Box file names. When downloading from Vagrant Cloud, you don't need to specify the URL.
// Create a Vagrantfile by specifying the Box file
$ vagrant init hashicorp/bionic64
// Start the VM
$ vagrant up
// Check VM status
$ vagrant status
// Connect via SSH
vagarnt ssh
// Destroy the VM
$ vagrant destroy
By simply running the vagrant up command, everything needed for the project (installing software with dependencies, setting up networking, synced files, etc.) will be prepared, allowing you to work comfortably on your own machine!
2. Install Vagrant
Installing Vagrant for your OS environment
Note: If you haven't installed it in the previous chapter, please do so now.
Verify the installation
Open your terminal and try typing one of the following three commands.
$ vagrant
$ vagrant -h
$ vagrant -v
Note
Some OS distributions include a vagrant package in their upstream package repositories. In such cases, please do not use the distribution's package manager for installation (as dependency issues may arise). Please use the official download page.
3. Initialize a Project Directory
Creating the Vagrantfile
(1) Specify your project's root directory. Many of Vagrant's configuration options are relative to this root directory.
(2) Describe the type of machine and resources your project needs. Similarly, describe what software you want to install and how you want to access it.
- Create a directory
// Create the vagrant_getting_started directory
$ mkdir vagrant_getting_started
// Move to the vagrant_getting_started directory
$ cd vagrant_getting_started
- Initialize the directory
$ vagrant init hashicorp/bionic64
vagrant init (which is a built-in function) takes a box file name and URL as arguments.
This should create a Vagrantfile in the same directory. This file is intended to be version-controlled, allowing new team members to set up their environment immediately using this Vagrantfile.
4. Install and Specify a Box
In Vagrant, you can quickly clone a virtual machine by using a base image (image file).
These base images are known as Boxes in Vagrant. Specifying a Box is always one of the first tasks after creating a Vagrantfile.
Installing a Box file (Optional)
While this step is generally unnecessary for the commands you'll learn later, it can be useful if you want to install a box file without creating a Vagrantfile first. Here is how to install a Box file:
$ vagrant box add hashicorp/bionic64
$ vagrant box add username/boxname
Boxes are stored globally for the current user. Each project can then use these boxes as an initial image. (This means that if two projects use the same Box file and you add a file in one, it won't affect the other.)
The box file section can be replaced with a URL or a local file path.
Using a Box file
Open the Vagrantfile and specify the Box file name in config.vm.box.
Even if the box hasn't been added beforehand, Vagrant will automatically download and add it upon startup. (That's why the manual Box addition mentioned above is usually not required.)
You can also explicitly specify a version using config.vm.box_version or config.vm.box_url (neither is required).
Vagrant.configure("2") do |config|
config.vm.box = "hashicorp/bionic64"
config.vm.box_version = "1.0.282" #-> optional: config.vm.box_version = "1.0.282"
#config.vm.box_url = "https://vagrantcloud.com/hashicorp/bionic64"
end
Finding Other Boxes
You can find more at Vagrant Cloud!
Note: Paid accounts allow for publishing private Boxes within an organization, but we will skip that for now.
5. Boot an Environment
- Boot the VM (Virtual Machine)
Running the following command should bring up an Ubuntu-based VM in about a minute:
$ vagrant up
[Supplement] Checking VM Status via Command and GUI
First, check the status using a command:
$ vagrant status
Next, confirm that the VM is running via a GUI (Graphical User Interface).
Modify the Vagrantfile so that VirtualBox opens upon startup.
// Uncomment two lines to enable GUI mode
config.vm.provider "virtualbox" do |vb|
# # Display the VirtualBox GUI when booting the machine
vb.gui = true
#
# # Customize the amount of memory on the VM:
# vb.memory = "1024"
end
This should make VirtualBox launch automatically.
However, it's recommended to operate via SSH (as shown in the official docs) because you can use your regular terminal, which is much easier!
Connecting via SSH
Let's try SSHing into the virtual machine you just started.
$ vagrant ssh
To exit the SSH session, type exit or logout, or press Ctrl + D.
Once connected via SSH, verify that the Vagrantfile exists:
[vagrant@localhost ~]$ pwd
/home/vagrant
[vagrant@localhost ~]$ cd ../../
[vagrant@localhost /]$ ls
bin dev home lib64 media opt root selinux swapfile tmp vagrant
boot etc lib lost+found mnt proc sbin srv sys usr var
[vagrant@localhost /]$ ls vagrant/
Vagrantfile
[vagrant@localhost /]$
WARNING!!
Never run rm -rf / just because it's a virtual machine!! This is because Vagrant shares the directory at /vagrant with the directory on your host machine that contains your Vagrantfile, and this would be deleted too! Details about shared folders will be explained in the next section.
Destroying a Virtual Machine
Exit the SSH connection and delete all resources created when the machine was made.
$ vagrant destroy
default: Are you sure you want to destroy the 'default' VM? [y/N] y -> Input y!
==> default: Forcing shutdown of VM...
==> default: Destroying VM and associated drives...
// Check vagrant status
$ vagrant status
Current machine states:
default not created (virtualbox)
The environment has not yet been created. Run `vagrant up` to
create the environment. If a machine is not created, only the
default provider will be shown. So if a provider is not listed,
then the machine is not created for that environment.
// By the way, the Box file is not gone
$ vagrant box list
hashicorp/bionic64 (virtualbox, 1.0.282)
Deleting the Box file
$ vagrant box remove hashicorp/bionic64
Removing box 'hashicorp/bionic64' (v1.0.282) with provider 'virtualbox'...
By now, you have learned the general cycle of environment construction, operation, and destruction in Vagrant.
In the next section, let's learn how to synchronize files between your local PC and the (guest) virtual machine.
6. Synchronize Local and Guest Files
Not many people want to edit files in a plain vim editor over an SSH connection.
Vagrant automatically synchronizes files between your local machine and the SSH guest PC.
This allows you to execute files edited locally within the virtual development environment.
By default, Vagrant shares your project directory (the directory where you created the Vagrantfile with vagrant init in section 3) to the /vagrant directory on the guest machine.
Now, let's check how file sharing between the guest machine and the local PC is actually performed.
Observing Shared File Behavior
Note: The home directory when you run vagrant ssh, which is /home/vagrant, is different from the local file sharing destination. (The sharing destination is the /vagrant directory directly under the root.)
First, connect via SSH and move to the /vagrant directory.
$ vagrant ssh
$ cd ../../vagrant
$ pwd
->/vagrant
Create a new file named hoge in the /vagrant directory.
$ touch hoge
Now you can confirm that the hoge file also exists in your local project directory!
$ exit
logout
$ ls
Vagrantfile hoge
With synced folders, you can continue to use your own editor on your host machine and have the files sync into the guest machine.
Next, let's create a file named fuga.html on the local machine and see if that file is synchronized on the VM as well.
First, create the file locally.
$ touch fuga.html
$ ls
Vagrantfile hoge fuga.html
Next, edit the contents of fuga.html with your favorite editor.
<p>Is it edited correctly?</p>
You can confirm that fuga.html exists at the SSH destination as well!
$ vagrant ssh
$ cd ../../
$ ls vagrant/
Vagrantfile hoge fuga.html
// Check the contents of fuga.html (you can also use the view command)
$ cat vagrant/fuga.html
<p>Is it edited correctly?</p>
In the next section, let's learn how to use provisioning to install packages, users, and various other things.
7. Provision a Virtual Machine
In this section, we will use provisioning to turn our VM into a web server.
Create an HTML directory on the local machine
Create an html directory in ~/Desktop/vagrant_test.
$ mkdir html
Next, create an index.html file in the html directory.
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vagrant</title>
</head>
<body>
<h1>Starting Vagrant!</h1>
</body>
</html>
Note: If you don't specify the character code in meta tags, Japanese text might be garbled!
Let's write a provisioning script!
In this tutorial, we will set up Apache (as a web server) using a shell script. First, save the following shell script as bootstrap.sh.
#!/usr/bin/env bash
apt-get update
apt-get install -y apache2
if ! [ -L /var/www ]; then
rm -rf /var/www
ln -fs /vagrant /var/www
fi
This script will download and start Apache.
Furthermore, it creates a symbolic link between the "synced folder directory" and the "location where the Apache server looks for content to serve as a response."
[Supplement] Shell Script
- Script after #!
The script after #! on the first line is called a Shebang, and it specifies the interpreter (a program that interprets and executes source code). In this case, it tells the computer, "please interpret this as a bash script."
Using /bin/bash is also fine. The explanation at this link is easy to understand!
For more on env, I recommend "Understanding shebang by doing"!
- apt-get
apt-get is a package management system for Debian. (The Ubuntu we are using is also a Debian-based Linux.) It's like Homebrew on Mac.
Starting from Ubuntu 14.04, the apt command is recommended instead of apt-get. As mentioned in linked explanations, the apt command is generally easier for users.
- Regarding the script after "if"
Shell scripts might seem confusing, but you can think of it as the following if statement structure:
Reference: [Shell Script] How to use if for conditional branching!
if [ condition1 ]; then
processing for condition1
elif [ condition2 ]; then
processing for condition2
else
processing if neither condition1 nor 2 is met
fi
condition1 corresponds to ! [ -L /var/www ]. -L means "true if the file exists and is a symbolic link," and ! represents logical negation (equivalent to false if !true).
In other words, it means "run the process if the file at the /var/www directory does not exist as a symbolic link."
From the above, this shell script will:
The first time: "Since the symbolic link /var/www does not exist (if a regular /var/www directory exists, delete it first), create /var/www as a symbolic link to /vagrant."
The second time: "Since the symbolic link /var/www already exists, run the process after else (which is nothing in this case)."
Now, let's get bootstrap.sh to run.
Setting up Vagrant to Run bootstrap.sh
Let's configure Vagrant so that this script runs when the VM is set up!
Add the following config.vm.provision line to your Vagrantfile.
Vagrant.configure("2") do |config|
config.vm.box = "hashicorp/bionic64"
config.vm.provision :shell, path: "bootstrap.sh"
end
This tells Vagrant to use bootstrap.sh as a shell provisioner.
Provisioning the Web Server
If you haven't started the virtual machine yet, simply running vagrant up will cause Vagrant to automatically perform provisioning using bootstrap.sh.
However, if the virtual machine is already running, you can reload it as follows to make it work.
(Since provisioning is only performed during the initial vagrant up, simply running vagrant up again won't work.)
$ vagrant reload --provision
Now, let's use the wget command at the SSH destination to retrieve the HTML file!
$ vagrant ssh
$ wget -qO- 127.0.0.1
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vagrant</title>
</head>
<body>
<h1>Starting Vagrant!</h1>
</body>
</html>
[Supplement] What is the wget Command?
According to @IT/Linux Basic Commands, wget is a command that "downloads a file by specifying a URL."
-q (--quiet) is an option to "not output progress messages."
-O file (--output-document=file) saves the downloaded file to the specified file. (Similar to specifying the save destination with a redirect.) Also, specifying - as the file will output the content to standard output.
This works because the shell script we set up earlier performs "installing Apache" and "setting the /vagrant directory as the Apache Document Root."
[Supplement] Apache Document Root
By default, the Apache web server is configured to look in the /var/www directory for files and data to manage and return as responses to web browsers. (This managed directory is called the Document Root.)
In this case, since /var/www is a symbolic link to /vagrant, modifying the contents of /vagrant will naturally reflect changes in the files under the Apache Document Root.
In the next tutorial, we will handle networking. Let's try accessing the website provided by the guest machine by forwarding a port to it.
When Provisioning Scripts Become Too Complex
For provisioning scripts, it is more efficient to package a custom Vagrant box with packages already installed rather than building it every time. Details can be found here.
8. Configure the Network
Port forwarding allows you to specify a port on the guest machine and share it through a port on the host machine.
By configuring port forwarding, you can access the guest machine's Apache web server. Add the config.vm.network line to your Vagrantfile...
Vagrant.configure("2") do |config|
config.vm.box = "hashicorp/bionic64"
config.vm.provision :shell, path: "bootstrap.sh"
config.vm.network :forwarded_port, guest: 80, host: 4567
end
*Note: The above means "forward access to port 4567 on the host OS to port 80 on the guest OS."
Let's reload.
$ vagrant reload
Once the virtual machine restarts, try accessing http://127.0.0.1:4567.

As you can see, we were able to access it successfully!
By the way, Vagrant has other networking modes, such as assigning a static IP address to the guest machine or bridging the guest machine to an existing network. If you are interested in other networking modes, please read the Networking page.
9. Share an Environment
In addition to providing development environments, Vagrant makes sharing and collaborating on these environments easy. This core feature is called Vagrant Share.
Vagrant Share is a plugin. This plugin makes it possible to share your Vagrant environment with anyone in the world via the internet. Vagrant Share provides a URL that routes directly to your Vagrant environment from any device in the world connected to the internet.
Prerequisites
ngrok must be installed.
→ This is a tool used when you want to show a site you are creating in a local environment over the internet.
For those who want a quick overview, I recommend @Esfahan's Qiita article, "How to use ngrok (Windows, Mac)".
Installing the Plugin
Let's install Vagrant Share.
$ vagrant plugin install vagrant-share
Sharing the Environment
$ vagrant share
Open a web browser and visit the URL provided in your output! The page served by the Apache server you already created should load! (Naturally, if you modify the files and reload the URL, the changes will be reflected!) This page can be accessed from any device in the world!
Finally, don't forget to end the session.
$ ^C
==> default: Halting Vagrant share!
Now, if you reload the URL, the page should no longer be accessible!
For more information on Vagrant Share, see here.
In the next chapter, let's learn about the teardown process!
10. Teardown an Environment
In this section, let's actually perform the following on the virtual environment we have built and modified:
(1) Suspend [Pause] vagrant suspend
(2) Halt [Shutdown] vagrant halt
(3) Destroy vagrant destroy
Which option you use depends on how long you intend to stop the virtual environment you use for work and how quickly you want to restart it.
(Naturally, the time to restart increases in the order of suspend → halt → destroy.)
If you haven't started Vagrant yet, please do so.
$ vagrant up
$ vagrant status
-> default running (virtualbox)
(1) Suspending the Virtual Machine
First, let's suspend the virtual machine using vagrant suspend.
$ vagrant suspend
==> default: Saving VM state and suspending execution...
$ vagrant status
-> default saved (virtualbox)
The vagrant suspend command allows you to quickly pause and restart the VM.
By running vagrant up, the VM will start again in the same state it was in before it was stopped.
$ vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Checking if box 'hashicorp/bionic64' version '1.0.282' is up to date...
==> default: Resuming suspended VM...
##... output truncated ...
(2) Fully Stopping the Virtual Machine
Next, let's stop the virtual machine using vagrant halt.
$ vagrant halt
$ vagrant status
-> default poweroff (virtualbox)
This safely shuts down the guest machine's OS and powers down the VM itself. The contents of the disk are also properly preserved.
Let's restart it to confirm.
$ vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Checking if box 'hashicorp/bionic64' version '1.0.282' is up to date...
==> default: Clearing any previously set forwarded ports...
==> default: Clearing any previously set network interfaces...
==> default: Preparing network interfaces based on configuration...
##... output truncated ...
However, restarting a fully stopped virtual machine takes some time because it performs a cold boot, and it also consumes disk space while stopped.
(3) Deleting the Virtual Machine
When you run vagrant destroy to delete the virtual machine, all traces of the guest machine are removed from your local machine. Regain disk space and RAM (that the guest machine was consuming) by stopping the guest machine and powering it down.
$ vagrant destroy
default: Are you sure you want to destroy the 'default' VM? [y/N] y
==> default: Forcing shutdown of VM...
==> default: Destroying VM and associated drives...
As shown above, enter "y" (yes) at the prompt after the vagrant destroy command.
Even from this state, you can start the virtual machine again by running vagrant up. However, it will take time to start, and the previous state will have been discarded.
11. Rebuild an Environment
(With Vagrant) no matter how much time passes since you left the project, you can immediately spin up (start) the environment.
The method is simple.
$ vagrant up
That's it! The Vagrant environment is already fully configured via the Vagrantfile. Therefore, development members can replicate your work environment at any time just by running the vagrant up command.
This completes the general lifecycle of environment construction using Vagrant!
In the final chapter, let's also touch upon providers other than VirtualBox!
12. Explore other Providers
Installing a New Provider
Please refer to the official documentation for each provider regarding their specific settings!
Starting with a New Provider
Once you have installed a new provider, you just need to run the following command.
(There is no need to mess with the Vagrantfile!)
$ vagrant up --provider=vmware_desktop
Once you specify another provider and run vagrant up as shown above, other Vagrant commands will automatically use the specified provider!
So, for example, once you are ready for SSH connection or to delete the virtual machine, you can run commands normally (as you did in previous chapters) without any issues.
If you want to learn more about providers, please refer to this page (the official documentation in English).
Discussion