Deploying a REST API and Its Dependent Services on Bare Metal Using Vagrant

ยท

2 min read

Deploying a REST API and Its Dependent Services on Bare Metal Using Vagrant

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:

  1. VirtualBox

  2. Vagrant

  3. 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:

  1. Steps for installing Vagrant on a desired OS -> Install Vagrant

  2. Create a new directory and navigate into it:

     mkdir vagrant-rest-api && cd vagrant-rest-api
    
  3. Initialize Vagrant with Ubuntu 18.04 LTS (Bionic Beaver) as the base box:

     vagrant init hashicorp/bionic64
    
  4. Start the Virtual Machine:

     vagrant up
    

Step 3: Provisioning the VM

  1. Create a script.sh file in your project directory. This script will contain all the necessary commands to install dependencies on the VM.

  2. Modify the Vagrantfile to use this script for provisioning:

     config.vm.provision "shell", inline: "/bin/bash /vagrant/script.sh",
       run: "once"
    
  3. 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:

  1. Add the following line to your Vagrantfile:

     config.vm.network "forwarded_port", guest: 8080, host: 8080
    
  2. Reload the Vagrant configuration:

     vagrant reload
    

Step 5: Testing the Setup

  1. SSH into your Vagrant box and navigate to the project directory:

     vagrant ssh
     cd /vagrant/SRE-Bootcamp-Web-Server/
    
  2. Start your Docker Compose setup:

     sudo docker compose --profile DB up --build -d
    
  3. 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.

ย