Provision a virtual machine
Vagrant allows you to automatically provision environments, including web servers. Before automatic provisioning, you would SSH into your guest machine and install a webserver. This process was manual and would need to be repeated every time you shut down and brought this environment back up. Vagrant automatically installs software when you use vagrant up
so that the guest machine can be repeatably created and ready-to-use.
In this tutorial, you will serve local files using a webserver on a guest machine.
Prerequisites
- Install the latest version of Vagrant.
- Install a virtualization product such as: VirtualBox, VMware Fusion, or Hyper-V.
VMware Fusion: There is an additional plugin and configuration required, review the documentation for guidance. Also, note that it is in tech preview for Apple Silicon.
Create an HTML directory
On your local machine, create a directory from where Apache will serve your content.
Next, create the file index.html
in the new directory with the contents for the index page.
Write a provisioning script
Set up Apache with a shell script. Create the following shell script
and save it as bootstrap.sh
in the same directory as your Vagrantfile.
This script downloads and starts Apache, and creates a symlink between your synced files directory and the location where Apache will look for content to serve.
Configure Vagrant
Next, edit the Vagrantfile to use the script when you provision the environment.
The provision
line configures Vagrant to use the shell
provisioner
to set up the machine with the bootstrap.sh
file. The file path is relative
to the location of the project root which should be the location of the Vagrantfile.
Deploy the webserver
Use vagrant up
to create your machine and have Vagrant automatically provision it.
Verify deployment
After Vagrant completes provisioning, the web server will be active. You cannot see the website from your own browser yet, but you can verify that the provisioning works by loading a file from within the machine.
SSH into the guest machine.
Now get the HTML file that was created during provisioning.
This works because in the shell script above you installed Apache and
setup the default DocumentRoot
of Apache to point to your /vagrant
directory, which is the default synced folder setup by Vagrant.
Continue to the next tutorial where you will forward a port on your guest machine so that you can access the website that the guest machine is serving.
Logout of your SSH session.
Next steps
For complex provisioning scripts, it may be more efficient to package a custom Vagrant box with those packages pre-installed instead of building them each time. Learn more in the packaging custom boxes documentation.
You have successfully provisioned your first virtual machine with Vagrant. Read on to learn about networking.