How to host Angular Application on Azure Cloud Platform & Basics of Azure CP.

1.1. Introduction

1.1.1. About the Cloud Service Platform

Microsoft Azure is a public cloud computing platform with solutions including Infrastructure as a Service (IaaS), Platform as a Service (PaaS), and Software as a Service (SaaS) that can be used for services such as analytics, virtual computing, storage, networking etc.

1.1.2. Terminologies and its definition

Here, before implementing any services or functions we need to understand the fundamentals of what these services/applications are.

1.1.2.a. Virtual Machine

A virtual machine (VM) is a virtual environment that functions as a virtual computer system with its own CPU, memory, network interface, and storage, created on a physical hardware system. Software called a hypervisor separates the machine's resources from the hardware and provisions them appropriately so they can be used by the VM.

1.1.2.b. Storage Service

Cloud storage service is a cloud computing service offering in which data can be stored, edited and retrieved from a remote cloud storage server over the Internet under a utility computing model.

In Azure, there are a lot of storage services available depending on the usage capacity and functionalities.

1.1.2.c. Public IP

A public IP address is an IPv4 address that is reachable from the internet. If a resource in your tenancy needs to be directly reachable from the internet, it must have a public IP address. Depending on the type of resource, there might be other requirements.

1.1.2.d. Databases

Microsoft Azure offers a choice of fully managed relational, NoSQL, and in-memory databases, spanning proprietary and open-source engines, to fit the needs of modern app developers. That Focuses on building applications while Azure manages databases making the job simpler by surfacing performance insights through embedded intelligence, scaling without limits, and managing security threats.

1.1.2.e. Resource Group

Azure Resources Groups are logical collections of virtual machines, storage accounts, virtual networks, web apps, databases, and/or database servers.

2.1. Implementation

The Microsoft Azure account is created on a personal Gmail using the coupon code provided by the student ambassador for Microsoft Azure Student access privileges.

One thing about Microsoft Azure is that the console management UI is very easy to navigate and intuitive. However, I have described each process in a point with proper explanation so that the order is maintained and the learning curve is less.

2.1.1. Creating a resource group

Since I have already defined what a resource group is, let's talk about how we can create it. Creating a resource group is a necessary step before creating a server in a virtual machine because that machine needs to be in a collective environment called 'Resource Group'. You can access the resources section by clicking on the resource group section which would lead you to its respective section where you can create a custom group.

Resource Group: prajeetStudent
Region: East US

2.1.2. Creating a Virtual Machine

To host any application or server we need a machine that allows us to process and give a platform. For that we will be creating a server using VM. I am comfortable working with Linux Distributions, so I have chosen the linxus OS. However, you can choose any OS or distribution you are interested in. The reason why we needed a resource group is because we will be using that group in this form to hold this VM.

Similarly, fill the required information to create the virtual machine. It is recommended that you choose the region closer to your country to gain much efficiency, Leave the disks and networking settings as default and create a virtual machine. However, make sure you remember your password and username.

2.1.3. Booting a Virtual Machine on Putty

PuTTY allows the use of SSH (Secure Shell) to access a remote computer. It is a software terminal emulator that supports VT100 emulation, telnet, SSH, kerberos, and serial port connections.

2.1.3.a. Installing Putty on your local machine.

Firstly open your terminal, Enter the following commands.

sudo apt-get update
sudo apt install -y putty

Once you install the putty, search and open it. And Put the Public IP on port 22 and load it.

If you don't know your SSH, you can go to the connect section and find out how you can boot. Remember to save the hostname and port for future uses.

The putty command line is just like your Window's Command Line or your Linux Terminal. The commands are similar to the linux terminal commands.

2.1.4. Hosting an Application on the Machine

Now we have a virtual machine on Azure Cloud Platform with Linux OS, where you can imagine this being your own PC in the cloud that can be accessed anywhere.

To host something like a web application we need to create a web server and there are several open-source web servers that you can use. A web server is computer software and the underlying hardware that accepts requests via HTTP, the network protocol created to distribute web pages or its secure variant HTTPS. A user agent, commonly a web browser or web crawler, initiates communication by making a request for a specific resource using HTTP, and the server responds with the content of that resource or an error message.

I will be using Apache 2 as a cross browser and platform web server to host and deploy an application that I made last semester called "Fare Optimizer".

2.1.4.a. Installing apache2 on your Virtual machine.

sudo apt update
sudo apt install apache2

2.1.4.b. Setting up your application.

By default, Apache comes with a basic site enabled. We can modify its content in /var/www/html or settings by editing its Virtual Host file found in /etc/apache2/sites-enabled/000-default.conf.

So let's start by creating a folder for our new website in /var/www/ by running the del command to delete the default index.html file and uploading the SSPA Application that has been built for the production stage.

service apache2 stop
rm -r /var/www/index.html

Similarly, we need the angular SSPA from our local machine to our virtual machine, for that to make a zip of the production file. In your local terminal which is in your application folder.

ng build --prod
tar -czvf Fare-Calculation.tar.gz dist/Fare-Calculation

Now that we have zipped it, we need to push this tar.gz compressed file to our VM, we can do so by executing the following command.

scp -P 22 dist/Fare-Calculation.tar.xz prajeet@40.85.189.22:/home/prajeet

Once it is copied, go back to your putty and unzip and move it to the root folder of apache2 and start the web server.

tar -xvf Fare-Calculation.tar.xz
mv Fare-Calculation.tar.xz /var/www/
service apache2 start

Just setting up the web service is not going to solve your problem, if you now visit your public IP address, you will still get an error message and to solve that problem. We need to create some networking rules.

2.1.4.c. Creating an Inbound Networking rule for http port.

we need to go to the VM networking setting and create an InBound rule for port 80 which is an http port.

Once you do that you will be able to access you deployed application on your public IP address, and mine is: 40.85.189.22

2.1.5. Storage Service on the Virtual Machine

I have already defined what a storage service is, so let's talk about how we can link a file storage service to our newly created virtual machine. Before that, we need to create a storage account which can be done by creating a new resource under the resource group prajeetStudent.

Once your deployment is completed you can go to the storage resource and create a file shared folder which would be a storage service between VM and resource group.

The form can be opened by clicking on the data storage > File Share > + File Share. Similarly, once created, go inside and click on the 'Connect' button. Where you will be given a script that needs to be copy-pasted into your VM terminal.

2.1.6. Creating Database on the Virtual Machine

As already mentioned in the definition of the database, I will be creating a NoSQL Database that has key and value properties. This can be achieved by using Azure Cosmos Database Service. The process of creating a database is as simple as it gets in the Azure console. Find the Azure Cosmos DB Service and Create a new database. However you need to create a service first before you create a DB, so be careful of that.

You can also create a template NodeJs, Python, JAVA project, from the console. From the quick start section.

2.1.7. Communicate with the application & database via Virtual Machine

To communicate between the DB and the application, there needs to be a medium through which the data is transferred. To establish a connection between two, we need to create a web service API. Let's create an API that communicates with the Azure Cosmos DB to get the application general information. The API will be created using NodeJs and Express.

To create a nodejs project:

mkdir fareOptimizerAPI
cd fareOptimizerAPI
npm init --yes

we also need some dependencies like, express, @azure/cosmos

npm i @azure/cosmos
npm i express

Source Code To Get The Data from Azure Cosmos DB (query.js)

const CosmosClient = require('@azure/cosmos').CosmosClient;
const url = require('url');
const endpoint = 'https://languye-sql-nb3.documents.azure.com:443/';
const key = '*************************';
const databaseId = 'TransportationFareOptimizer';
const containerId = 'Items';
const partitionKey = { kind: 'Hash', paths: ['/partitionKey'] };
const options = {
  endpoint: endpoint,
  key: key,
  userAgentSuffix: 'CosmosDBJavascriptQuickstart',
};
const client = new CosmosClient(options);

exports.QueryContainer = async () => {
  const querySpec = {
    query: 'SELECT * FROM root',
  };
  const { resources: results } = await client
    .database(databaseId)
    .container(containerId)
    .items.query(querySpec)
    .fetchAll();
  return results;
};

For privacy reasons, I have not given the key value, but you can find your in your DB endpoint section. Similarly, for the main app.js

const express = require('express');
const app = express();
const query = require('./query.js');

app.get('/getInfo', async (req, res) => {
  const list = await query.QueryContainer();
  if (list !== undefined || list !== null) {
    res.send(list);
  } else {
    res.status(500).send('Server Error');
  }
});

const port = process.env.PORT || 3000;

app.listen(port, () => {
  console.log(`listening on port ${port}`);
});

Similarly, we will deploy this code into Microsoft App Service from VS Code Extension and intuitive setup. Finally, we have created an API that gets the Application Information from the Database.

API: http://fareoptimizerapi.azurewebsites.net/getInfo

API Documentation

[
  {
    "authorName": "Prajeet Shrestha",
    "authorContact": "prajeet.shrestha.biz@gmail.com",
    "applicationName": "Transportation Fare Optimizer",
    "applicationVersion": "@1.0",
    "id": "931a39ec-952a-4d36-aa75-c1121b2bfe95",
    "_rid": "KTRgAPUXc04BAAAAAAAAAA==",
    "_self": "dbs/KTRgAA==/colls/KTRgAPUXc04=/docs/KTRgAPUXc04BAAAAAAAAAA==/",
    "_etag": "ee01b5b3-0000-0800-0000-60fadfe20000",
    "_attachments": "attachments/",
    "_ts": 1627054050
  }
]

Now this API can be called by any application under any instances or machines.


Want to read more?

View all