Tutorial

How to Host a MEAN Stack App on DigitalOcean

Updated on September 15, 2020
Default avatar

By Noman Ur Rehman

How to Host a MEAN Stack App on DigitalOcean

This tutorial is out of date and no longer maintained.

Warning: For the latest information, refer to the documentation for creating DigitalOcean Droplets.

Introduction

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 DigitalOcean.

In this tutorial, you will learn.

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

A Word on DigitalOcean

Screenshot of the DigitalOcean home page.

So what really is DigitalOcean? From DigitalOcean’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.

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

Some of its 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.

  1. 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.

Screenshot of the output of the  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 DigitalOcean 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, DigitalOcean only accepts credit cards. Debit cards and prepaid cards 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.

Screenshot of the Droplets section with a Create Droplet button.

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.

Screenshot of choosing an distribution for a Droplet. Ubuntu is selected.

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

Screenshot of choosing a one-click app for a Droplet. MEAN 0.5.0 on 16.04 is selected.

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.

Screenshot of choosing a size for a Droplet. Five dollars a month is selected.

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.

Screenshot of choosing a datacenter region. Frankfurt, Germany is selected.

In our case, it is really up to 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.

Screenshot of the 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.

Screenshot of the New SSH key prompt.

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.

Screenshot of the Finalize and create section. The number of droplets is set to: 1. The hostname is set to: scotch-mean-tutorial. The tags is set to: great-app-that-will-change-the-world.

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.

Screenshot of the progress for Droplet creation. A bar is partially filled to indicate estimated time remaining.

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.

  1. ssh -i <path-to-your-key-file> root@<your-droplet-ip>

You can recall the path of the key file from the Creating an SSH Key section. 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 Droplets section.

Screenshot of the list of Droplets. IP address, creation date, and tags are displayed.

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 the Node version:

  1. node -v
Output
v6.9.2

View the npm version:

  1. npm -v
Output
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.

The sample application is located at /opt/mean:

  1. cd /opt/mean

Start the sample application:

  1. npm start
Output
> meanjs@0.5.0 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 sign in and sign up 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 DigitalOcean’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.

  1. 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.

  1. npm install -g pm2

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

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

  1. rm -rf /opt/mean

Move to /opt:

  1. cd /opt

Cloning repository at /opt/mean

  1. git clone https://github.com/<your-git-username>/MeanMapAppV2.0.git "mean"

Move to the project root.

  1. cd /opt/mean

Install npm modules.

  1. npm install

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

  1. pm2 start server.js

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

Conclusion

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

I encourage you to explore DigitalOcean 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!

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors
Default avatar
Noman Ur Rehman

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
Leave a comment


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more
DigitalOcean Cloud Control Panel