In this blog post, we'll walk through the process of setting up a REST API along with its dependent services using Vagrant for virtualization. This setup includes a load balancer, two web servers, and a PostgreSQL database.
Prerequisites
Before we begin, make sure you have the following installed on your host machine:
VirtualBox
Vagrant
Docker and Docker Compose
Step 1: Setting Up the Architecture with Docker Compose
First, let's create our application architecture using Docker Compose. This setup includes:
NGINX as a load balancer (exposed on port 8080)
Two web servers (ws-1 and ws-2, exposed on ports 8081 and 8082 respectively)
A PostgreSQL database (exposed on port 5432)
Test this setup on your host machine to ensure it's working correctly.
Step 2: Install and Initialize Vagrant
Now, let's set up our Vagrant environment:
Steps for installing Vagrant on a desired OS -> Install Vagrant
Create a new directory and navigate into it:
mkdir vagrant-rest-api && cd vagrant-rest-api
Initialize Vagrant with Ubuntu 18.04 LTS (Bionic Beaver) as the base box:
vagrant init hashicorp/bionic64
Start the Virtual Machine:
vagrant up
Step 3: Provisioning the VM
Create a
script.sh
file in your project directory. This script will contain all the necessary commands to install dependencies on the VM.Modify the
Vagrantfile
to use this script for provisioning:config.vm.provision "shell", inline: "/bin/bash /vagrant/script.sh", run: "once"
Run the provisioning:
vagrant provision --provision-with shell
Step 4: Configuring Port Forwarding
To access our API from the host machine, we need to set up port forwarding:
Add the following line to your
Vagrantfile
:config.vm.network "forwarded_port", guest: 8080, host: 8080
Reload the Vagrant configuration:
vagrant reload
Step 5: Testing the Setup
SSH into your Vagrant box and navigate to the project directory:
vagrant ssh cd /vagrant/SRE-Bootcamp-Web-Server/
Start your Docker Compose setup:
sudo docker compose --profile DB up --build -d
From your host machine, open a web browser and navigate to:
http://localhost:8080/v1/healthcheck
If everything is set up correctly, you should see a response from your API.
Conclusion
We've successfully set up a development environment for a REST API with its dependent services using Vagrant and Docker. This setup allows for easy replication of the development environment and smooth collaboration among team members.
Remember to always test thoroughly before deploying to production, and consider security implications when exposing services to the internet.