How to Host a MEAN Stack App on Digital Ocean

0
954

Software development involves certain steps to be repeated overtime for different projects.

One of those steps is setting up the infrastructure for your web applications.

Since humans are easily annoyed with performing the same steps over and over, cloud computing is a giant leap towards saving humans the aforementioned annoyance.

There are many services available that provide you with a point and click interface to set up your application’s infrastructure within seconds, one of them is Digital Ocean.

In this tutorial, you will learn.

  1. Digital Ocean’s main features.
  2. How to create a droplet using Digital Ocean’s one-click install apps.
  3. Logging in to your droplet.
  4. Using git to deploy your application.

#A Word on Digital Ocean

So what really is Digital Ocean? From Digital Ocean’s official website.

DigitalOcean is a cloud infrastructure provider focused on simplifying web infrastructure for software developers.

Building software is complex, laying out the infrastructure to run software is even more complex.

Digital Ocean provides you with options that allow you to lay out your application’s infrastructure without a sweat.

Some of it’s key features are.

  1. Servers use high performance solid state drives. Their speed greatly enhances your application’s performance and setting up instances take less of your time.
  2. They have a very intuitive control panel that helps you perform a range of tasks.
  3. They have a very active community and their help pages are frequently updated and added to which means there is a great chance of help being readily available in case you get stuck.
  4. One-click installations allow you to spin up your preferred stack with a single click(as you will see later in this tutorial).

And the best among the lot is their prices are pretty easy on your wallet, starting at $5 per month.

#Creating an SSH Key

When we create our droplet, we are going to need to specify an SSH key in order to access it.

So let us have it ready before creating the droplet. Fire up your terminal and execute the following command.

$ ssh-keygen -t rsa

You will be prompted to enter the name of the file (with the full path) in which to save the key. This was shown to you when you generated the key and chose a place to save it. Usually the default is in your User folder and the /.ssh folder in there.

Once you have done that, skip the passphrase section by hitting enter twice.

Your private and public key will be created and all the essential details will be prompted on the screen.

The out of the `ssh-keygen -t rsa` command

The file that we are interested in, which will be used later when creating the droplet is the .pub file which is the public key that will be used for authentication. We will be using the contents of this file during the droplet creation process later.

Also, note down your computer’s name using the hostname command.

#Registering your Account

Before we get started, you should have a fully functional Digital Ocean account.

Registering an account is pretty simple.

Here is a walkthrough of the registration process.

  1. Adding your personal details along with your email address.
  2. Verifying your account using the email sent at your provided email address in step one.
  3. Adding your credit card details.

At the time of this writing, Digital Ocean only accepts credit cards. Debit cards and prepaid cards such as Payoneer will not work so be sure to have a credit card before getting started.

#Creating your Droplet

Once you have registered your account, move to the Droplets section at the dashboard and click the Create Droplet button.

Droplets section

In my case, I have not yet created a single droplet so your Droplet section may differ slightly considering you have created other droplets before.

Nonetheless, in either case, you should have the Create Droplet button.

The Create Droplets section further gives you the option to setup your application from scratch using the Distributions tab or use ready to use stacks under the One-click apps section.

Distributions section

We are going to use the MEAN 0.5.0 on 16.04 stack.

One-Click apps section

One-click apps provide a ready to use infrastructure configuration where our application’s environment is set up for us and we only need to focus on application deployment and stability.

Once you have clicked MEAN 0.5.0 on 16.04, scroll down to move to the Choose a size section.

Choose size section

Choosing a size depends on the type of application you intend to deploy so you will need to use a bit of your imagination to get through this part.

For example, if you are deploying a high traffic image service that provides cropping and resizing features to it’s users, you will need a high end configuration with lots of CPUs and disk space.

Similarly, a REST API can do with a medium configuration machine.

For our case, we are going to specify the very first $5/mo configuration with 1 CPU, 512MB RAM, 20GB SSD disk, and 1000GB data transfer.

Skip the Add block storage section.

The Choose a datacenter region section allows you to specify the physical location of your application.

Choose data center section

In our case, it is really upto your personal preference as we are deploying a single instance of our application. However, remember that this option is used in case you wish to deploy multiple instances of your application.

It helps reduce network latency as your users can be served from the nearest located instance of the application.

It can also help to have your application in multiple physical locations in case of a natural disaster such as an earthquake.

For some strange reason, I have always loved Germany hence I have chosen the Frankfurt datacenter.

You can skip the Select additional options section as well but if you are curious, you can hover over each option to view it’s description.

Moving to the Add your SSH keys section, we need to create an SSH key for our droplet in order to initiate remote shell sessions.

Add your SSH key section

It is a recommended security practice and whenever dealing with server communication, you should opt for it.

Click the New SSH Key button.

New SSH key section

In the New SSH Key form’s SSH key content field, paste in the contents of the .pub file that we created in the Creating an SSH Key section.

Also paste in the output of the hostname command in the Name field.

Click the Add SSH Key button to create your SSH key.

Finally, we need to specify the number of droplets and the hostname(for our droplet) in the Finalize and create section.

Finalize and create section

You can also add tags to easily identify your droplet such as the application’s name.

Click the Create button.

You will be taken back to the Droplets section where you will be shown the progress of the droplet creation process.

Droplet progress

#Logging in to your Droplet

Once your droplet is up and running, you can log in to it via SSH.

Secure Socket Shell, also called Secure Shell is just a fancy name for logging into your server’s terminal.

It allows server administrators to execute commands on target machines remotely.

Execute the following command to create a remote terminal session to your droplet.

$ ssh -i <path-to-your-key-file> [email protected]<your-droplet-ip>

You can recall the path of the key file from the Creating an SSH Keysection. Generally, it is the path of your public key file without the .pub extension.

You droplet IP address is visible next to your droplet in the Dropletssection.

Droplet IP

You will be prompted with a welcome message, followed by a blinking cursor ready to accept your commands.

Welcome message

Let us execute a few commands to make sure everything was setup correctly.

# view Node version
[email protected]:~# node -v
v6.9.2
# view NPM version
[email protected]:~# npm -v
3.10.9

Node and NPM seems to be working correctly.

Our droplet has a sample application that we can run to test things out.

# sample application is located at /opt/mean
[email protected]:~# cd /opt/mean
# start sample application
[email protected]:~# npm start

> [email protected] start /opt/mean
> gulp

[11:59:47] Using gulpfile /opt/mean/gulpfile.js
[11:59:47] Starting 'default'...
[11:59:47] Starting 'env:dev'...
                         .
                         .
                         .
MEAN.JS - Development Environment

Environment:     development
Server:          http://0.0.0.0:3000
Database:        mongodb://localhost/mean-dev
App version:     0.5.0
MEAN.JS version: 0.5.0
--

Notice that our application runs on port 3000.

Point your browser to http://<your-droplet-ip>:3000 and you will see the sample application’s welcome page.

Application homepage

The sample application is pretty functional with a signin and signup page.

Application sign in page

App signup page

Go ahead and have a play!

#MEAN.JS

MEAN is an acronym for MongoDB, ExpressJS, AngularJS, and Node.

They are separate modules that need to be set up if you wish to create an application that runs on this stack.

Just like Digital Ocean’s one-click MEAN stack installation installs the necessary software to host a MEAN stack application. Similarly, MEAN.JS sets up all the boilerplate code you need to get started with a MEAN stack application.

If you are interested in the concept, MEAN.JS’s Github page has all the details you need to get started.

#Hosting Node Applications

It’s nice to be alive in a time when mostly all major web programming languages provide a built-in server that can be used to quickly start your application during development and testing.

However, it is a bit risky and impractical to run your applications on the language’s built in server.

A simple case in point.

Web server softwares are built to function as full fledged web servers and allow complete control to the publisher through configuration files and runtime options.

For example, what if you need to configure the maximum POST data size? It is inefficient to handle it using your application’s file upload code and to let a request go through if it does not fulfill this configuration requirement.

Generally, in this case, we set up a reverse proxy to our application using a web server software.

We are going to see how we can do this using the Nginx web server.

Execute the following command to install Nginx.

[email protected]:~# sudo apt-get install nginx

Next, configure Nginx using the /etc/nginx/sites-available/default file.

server {
    listen 80;

    server_name <your-droplet-ip>;

    location / {
        proxy_pass http://<your-droplet-ip>:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
}

Restart Nginx service by executing the command sudo service nginx restart.

Point your browser to http://<your-droplet-ip> and you will see the sample application’s welcome page again.

Specifying the IP address only without the need to add port 3000 shows Nginx was setup correctly.

In other words, web browsers forward requests to port 80 by default and since we have Nginx running on port 80 ready to forward requests to the Node application, everything works as expected.

#Keeping your Application Alive

In the previous section, we saw why it is not a good idea to depend on Node’s built-in server. There is one more caveat to add to the equation.

Generally, a Node server does not restart itself.

Why would you need to restart a Node server, here is a little background.

When you write applications, there is always a chance you may miss a few error scenarios to handle in your code. For example, division by zero or a 404 response by a third party API.

In such cases, when exceptions are raised, a Node application breaks down and execution is halted.

Unless you plan to watch your application logs twenty four hours a day, you need to setup an environment where your application keeps running or is restarted in case of errors.

PM2 is a Node process manager that allows you to run your applications as a service in the background which is restarted whenever it goes down.

Execute the following command in your droplet to install PM2 globally.

[email protected]:~# npm install -g pm2

Then on, simply pass your application’s root file to the pm2 start command.

[email protected]:~# pm2 start app.js

#Deploying your Application

The last part we are going to look at is how to deploy your application to the droplet.

The sample application I am going to deploy has been taught to build in one of the previous tutorials by Ahmed Haque.

We can securely copy our application to the droplet using the scp command.

However, that is a bit inefficient so we are going to use git.

First, fork the sample application using Github.

Fork

Next, we are going to pull a copy of the code to our droplet at /opt/mean using the repository URL.

Repository URL

Be sure to remove the sample application first.

# remove sample application
$ rm -rf /opt/mean
# move to /opt
$ cd /opt
# cloning repository at /opt/mean
$ git clone https://github.com/<your-git-username>/MeanMapAppV2.0.git "mean"

Move to the project root.

$ cd /opt/mean

Install NPM modules.

$ npm install

Finally, execute the following command to start your application using PM2.

$ pm2 start server.js

Point your browser to http://<your-droplet-ip> and you should see the application’s home page.

#Curtains

In this tutorial, you saw how easy it is to launch a MEAN stack application using Digital Ocean.

I encourage you to explore Digital Ocean further and dive in deep with the sharks (see what I did there?).

I hope you found this tutorial interesting and knowledgeable. Until my next piece, happy coding!

Suggest

Angular, React.js & Vue.js – Quickstart & Comparison

ASP NET Core (ASP.NET 5),MVC 6,C#,Angular4 & EF Crash Course

Angular 2: From Theory to Practice 

LEAVE A REPLY

Please enter your comment!
Please enter your name here