How to Host a MEAN Stack App on Digital Ocean

How to Host a MEAN Stack App on Digital Ocean

How to Host a MEAN Stack App on Digital Ocean ... Helping millions of developers easily build, test, manage, and scale applications of any size – faster than ever before.🌟🌟🌟🌟🌟

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.

Table of Contents

  • A Word on Digital Ocean
  • Creating an SSH Key
  • Registering your Account
  • Creating your Droplet
  • Logging in to your Droplet
  • MEAN.JS
  • Hosting Node Applications
  • Keeping your Application Alive
  • Deploying your Application
  • Curtains

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

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.

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

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.

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.

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

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.

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

Click the New SSH Key button.

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.

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.

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

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

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.

The sample application is pretty functional with a signin and 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]otch-mean-tutorial:~# sudo apt-get install nginx

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

server {
listen 80;

server_name &lt;your-droplet-ip&gt;;

location / {
    proxy_pass http://&lt;your-droplet-ip&gt;: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.

Next, we are going to pull a copy of the code to our droplet at /opt/mean using the 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!

================================================================

Thanks for reading :heart: If you liked this post, share it with all of your programming buddies! Follow me on Facebook | Twitter

Learn More

☞ Learning MEAN Stack by Building Real world Application

☞ MERN Stack Front To Back: Full Stack React, Redux & Node.js

☞ Angular & NodeJS - The MEAN Stack Guide

☞ Master the MEAN Stack - Learn By Example

☞ NodeJs, MEAN Stack & MongoDB: JavaScript, AngularJS, Web Dev

☞ The Complete Node.js Developer Course (3rd Edition)

☞ NodeJS - The Complete Guide (incl. MVC, REST APIs, GraphQL)

☞ Node.js, Express & MongoDB Dev to Deployment




Mobile App Development Company India | Ecommerce Web Development Company India

Mobile App Development Company India | Ecommerce Web Development Company India

Best Mobile App Development Company India, WebClues Global is one of the leading web and mobile app development company. Our team offers complete IT solutions including Cross-Platform App Development, CMS & E-Commerce, and UI/UX Design.

We are custom eCommerce Development Company working with all types of industry verticals and providing them end-to-end solutions for their eCommerce store development.

Know more about Top E-Commerce Web Development Company

React Web Development: A Guide to Develop Progressive Web Applications

React Web Development: A Guide to Develop Progressive Web Applications

Outperform your competition with progressive web development and React.

Progressive web applications (PWAs) quickly gained popularity because they are web performance applications based on fast performance, streamlined to provide a mobile app-like experience. PWAs are built using HTML, CSS, and JavaScript to create a level of availability and performance equivalent to that of native mobile applications. They respond quickly, consume less data, store more space, and support push notifications and offline use in the browser.

Building a progressive web application has now become the web development trend that every business wants to follow. Significant players like Twitter and Flipboard have recently rolled out their progressive web apps to provide a mobile experience for users, without requiring them to install the app. In this article, you will learn how to build a progressive web application using React. Let's get started.

Step One — Set up the React Application

First, create a React application with create-react-app. To do so, you need to run the following commands:

  • npm install -g create-react-app
  • create-react-app pwa-app

Now, install React Router:

You need to replace the content of src / App.js using the code below to get a basic template with navigation.

import React, { Component } from 'react';
import { Router, browserHistory, Route, Link } from 'react-router';
import './App.css';

const NavBar = () => (
<div className="navbar">
<Link to="/">Feed</Link>
<Link to="/profile">Profile</Link>
</div>
);

const Template = ({ title }) => (
<div>
<NavBar />
<p className="page-info">
This is the {title} page.
</p>
</div>
);

const Feed = (props) => (
<Template title="Feed"/>
);

const Profile = (props) => (
<Template title="Profile"/>
);

class App extends Component {
render() {
return (
<Router history={browserHistory}>
<Route path="/" component={Feed}/>
<Route path="/profile" component={Profile}/>
</Router>
);
}
}
export default App;

Now, you'll have to update the default styles by replacing your src/App.css with the styles below to make your application look clean.

.navbar {
background-color: #01C8E5;
text-align: center;
}

.navbar a {
display: inline-block;
padding: 10px;
color: #fff;
text-decoration: none;
}

.page-info {
text-align: center;
font-weight: bold;
}

Then, run npm start to test the application in the browser. It is basically an application with two routes. Now, you will convert it to PWA.

Step Two — Lighthouse Setting and Auditing

Lighthouse is an automated open-source tool for testing applications against PWA checklists. It facilitates audits for accessibility, performance, and more.

Check your application with Lighthouse. Click the Lighthouse icon from the top right corner in Chrome and then click the "Create Report" button. The generated report will look like this:

Creating a report to test your PWA with Lighthouse

Fix all failed audits.

Step 3 — Sign Up for a Service Staff

Service employees are proxy servers that connect the application and the network. With Service Worker, you will have to block network requests and save cached files. It allows your application to work even with an unavailable system.

Create an empty worker.js file in your application's general directory and add the following code to that file.

// Flag for enabling cache in production
var doCache = false;

var CACHE_NAME = 'pwa-app-cache';

// Delete old caches
self.addEventListener('activate', event => {
const currentCachelist = [CACHE_NAME];
event.waitUntil(
caches.keys()
.then(keyList =>
Promise.all(keyList.map(key => {
if (!currentCachelist.includes(key)) {
return caches.delete(key);
}
}))
)
);
});

// This triggers when user starts the app
self.addEventListener('install', function(event) {
if (doCache) {
event.waitUntil(
caches.open(CACHE_NAME)
.then(function(cache) {
fetch('asset-manifest.json')
.then(response => {
response.json();
})
.then(assets => {
// We will cache initial page and the main.js
// We could also cache assets like CSS and images
const urlsToCache = [
'/',
assets['main.js']
];
cache.addAll(urlsToCache);
})
})
);
}
});

// Here we intercept request and serve up the matching files
self.addEventListener('fetch', function(event) {
if (doCache) {
event.respondWith(
caches.match(event.request).then(function(response) {
return response || fetch(event.request);
})
);
}
});

Now, check if the browsers support service staff and then register worker.js. To do this, you need to add the following script to the file public/index.html (note that shrink-to-fit=no in the viewport meta tag has been deleted).

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="theme-color" content="#000000">
<link rel="manifest" href="%PUBLIC_URL%/manifest.json">
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
<title>React App</title>
</head>
<body>
<noscript>
You need to enable JavaScript to run this app.
</noscript>
<div id="root"></div>
<script>
if ('serviceWorker' in navigator) {
window.addEventListener('load', function() {
navigator.serviceWorker.register('worker.js').then(function(registration) {
console.log('Worker registration successful', registration.scope);
}, function(err) {
console.log('Worker registration failed', err);
}).catch(function(err) {
console.log(err);
});
});
} else {
console.log('Service Worker is not supported by browser.');
}
</script>
</body>
</html>

You must restart your application and reload the browser after which you will see the Successful registration of member workers on the developer console. Now, recreate the Lighthouse report.

Step 4 - Improve the Progressive Nature of the Application

Your application will display an original blank div until the JavaScript loads and React hooks the original route. You must make sure your application works without downloading JS and displaying a bit of CSS and HTML before React takes effect. Your updated Index.html will look like this:

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="theme-color" content="#000000">
<link rel="manifest" href="%PUBLIC_URL%/manifest.json">
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
<title>React App</title>
<style type="text/css">
body {
margin: 0;
padding: 0;
font-family: sans-serif;
}
.navbar {
background-color: #01C8E5;
text-align: center;
}
.navbar a {
display: inline-block;
padding: 10px;
color: #fff;
text-decoration: none;
}
.page-info {
text-align: center;
font-weight: bold;
}
</style>
</head>
<body>
<noscript>
You need to enable JavaScript to run this app.
</noscript>
<div id="root">
<div class="navbar">
<a href="/">Feed</a>
</div>
<p class="page-info">
Loading an awesome app...
</p>
</div>
<script>
if ('serviceWorker' in navigator) {
window.addEventListener('load', function() {
navigator.serviceWorker.register('worker.js').then(function(registration) {
console.log('Worker registration successful', registration.scope);
}, function(err) {
console.log('Worker registration failed', err);
}).catch(function(err) {
console.log(err);
});
});
} else {
console.log('Service Worker is not supported by browser.');
}
</script>
</body>
</html>

Now, use Lighthouse to retest your application, and you'll see an improvement in the performance of the application.

Step 5 - Add the Splash Icon

You are required to add a 512x512 icon to display on the screen. To do so, you will have to update the manifest.json file and add the t0 icon to the public directory.

{
"short_name": "React App",
"name": "Create React App Sample",
"icons": [
{
"src": "icon-192x192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "icon-512x512.png",
"sizes": "512x512",
"type": "image/png"
}
],
"start_url": "/",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}

Also, use the following meta tags to allow the browser to determine that your application is a PWA.

<!-- Tell the browser it's a PWA -->
<meta name="mobile-web-app-capable" content="yes">
<!-- Tell iOS it's a PWA -->
<meta name="apple-mobile-web-app-capable" content="yes">
Step 6 — Implement PWA

Now, only HTTPS is missing, and the cache can be fixed after you deploy the application. Update the doCache flag with true in the worker.js file. Create a new project in the firebase dashboard and name it "Pwa Application." Then, run the following command in the project directory:

npm install -g firebase-tools
firebase login
firebase init

Your Firebase.json will look like this:

{
"hosting": {
"public": "build",
"rewrites": [
{
"source": "**",
"destination": "/index.html"
}
]
}
}

After initializing, building and deploying your application.

  • npm run build
  • firebase deploy

You will see results after you test the application using Lighthouse on the deployed URL.

Final product with Lighthouse

Finally, you have created your first progressive web application with React.js!

Originally published by Manoj Kumar Bardhan at  dzone.com

=======================================================

Thanks for reading :heart: If you liked this post, share it with all of your programming buddies! Follow me on Facebook | Twitter

Learn More

☞ Understanding TypeScript

☞ Typescript Masterclass & FREE E-Book

☞ React - The Complete Guide (incl Hooks, React Router, Redux)

☞ Modern React with Redux [2019 Update]

☞ The Complete React Developer Course (w/ Hooks and Redux)

☞ React JS Web Development - The Essentials Bootcamp

☞ React JS, Angular & Vue JS - Quickstart & Comparison

☞ The Complete React Js & Redux Course - Build Modern Web Apps

☞ React JS and Redux Bootcamp - Master React Web Development


Web Development Services

Web Development Services

As one of the best Web Application Development Company, it provides a fine quality mobile app development service at an affordable price. Especially, it encourage start-ups that have unique ideas, by offering a more competitive price

HireFullStackDeveloperIndia is rated as one of the top Web Application Development Company in India by various industry magazines and review sites. They have a right blend of award-winning designers, expert programmers and Google certified digital marketers which make them a unique one-stop solution for hundreds of our clients, spread across all countries.

A Good website reflects not only your business but also it is one of the main factors why a potential customer would convert into Client. A good website design helps increase traffic driving leads to grow business. The best web design company create a custom design for each corporate website so as to help them meet their business goals.

Get Quote: https://hirefullstackdeveloperindia.com/get-a-quote/