Deploy NodeJS applications to AWS or HEROKU
Tags: javascript, webdev, tutorial, beginners
Published: 2020-11-22 15:30:42

#<center><b>The Premise.</b></center>

NodeJS revolutionised the back-end architecture worldwide. Ryan Dahl made server side Javascript possible, further strengthening the position of JavaScript as an indelible part of the Web as we know it today.

![NodeJS](https://dev-to-uploads.s3.amazonaws.com/i/sutwo0vs54g2wblan6g8.png)

Starting at the grassroots level, often first-timers have to deploy their code to a production server, say for a Hackathon or some freelance work.

**Heroku** and **AWS** are the best choices for deployment right now, with their free plans nicely covering most of the needs for a first timer.

Yet, deployment is a maze of it's own. Procfiles, environment variables, proxy settings, port exposing, it's a dire  stretch for a person trying to spin up a server for the first time.

This article aims at helping you out to deploy your NodeJS apps.

But the bigger question is  where to deploy?

What exactly are the differences between Heroku and AWS? And what are the benefits of choosing one over the other?

##<center>***Heroku vs AWS***</center>

Heroku is container-base cloud platform offering (**PaaS**) whereas AWS is a secure cloud services platform providing **IaaS**, **PaaS** and **SaaS**.

(**I**nfrastructure/**P**latform/**S**oftware **a**s **a** **S**ervice)

Heroku is a easy to go solution for deploying if you are a beginner. You don’t have to actually worry about the infrastructure and scalability.

AWS in the beginning can be very complicated but gives you more control on the infrastructure of  your site. So if you are beginner it’s better to try Heroku than configuring so many things in the AWS instance when you can get one step deployment solution by using Heroku.

*So, let's begin, shall we?*

___

#<center>**Deploying NodeJS Apps on Heroku**</center>

![Heroku Logo](https://dev-to-uploads.s3.amazonaws.com/i/e5kk9w0eaprr4eg7e5ou.png)

We will use Heroku CLI for deploying. 

Download Heroku CLI from [here](https://devcenter.heroku.com/articles/heroku-cli).

After successfully installing the heroku cli run the following command:

```terminal
heroku login
```

Change the directory to the project folder.

###**Specifying a start script**

To determine how to start your app, Heroku first looks for a Procfile. If no Procfile exists for a NodeJS app, we will 
attempt to start a default web process via the start script in your package.json.

*What is a Procfile?* More on that below.

The command in a web process type must bind to the port number specified in the PORT environment variable. If 
it does not, the dyno will not start.

####***[What is a dyno?](https://devcenter.heroku.com/articles/dynos)***

>All Heroku applications run in a collection of lightweight Linux containers called dynos.

~ ***Heroku DEV center***

If you hardcode the port in your code, the deployment will fail.

Make sure you use process.env.PORT in your code.

###**Add a Procfile**

####***What is a Procfile?***

>Heroku apps include a Procfile that specifies the commands that are executed by the app on startup. You can use a Procfile to declare a variety of process types

~ *The [Heroku DEV center](https://devcenter.heroku.com/articles/procfile)*

The Procfile, is a list of custom commands which are defined by certain keywords like `web` or `worker`.

These are steps and commands which have to be executed each time your app is started. Heroku executes all the processes in your Procfile in different `dynos`, light-weight linux containers, which connect among each other.

Create file with name Procfile (no extension) and add the line.

```procfile
web: node index.js
```

###Build your app and run it locally

* Run the 'npm install' command in your local app directory to install the dependencies that you declared in your 
package.json file.

```bash
npm install
```

* Start your app locally using the Heroku local command, which is installed as part of the Heroku CLI.

```
heroku local web
```

Your app should now be running on http://localhost:5000/.

###Deploy your application to Heroku

After you commit your changes to git, you **can deploy your app to Heroku.**

```terminal
git add .
```

```
git commit -m "Added a Procfile."
```

```
heroku login
```

Enter your Heroku credentials.

```terminal
...
$ heroku create
Creating arcane-lowlands-8408... done, stack is cedar
http://arcane-lowlands-8408.herokuapp.com/ | git@heroku.com:arcane-lowlands-8408.git
Git remote heroku added
```

```
git push heroku master
...
-----> Node.js app detected
...
-----> Launching... done
       http://arcane-lowlands-8408.herokuapp.com deployed to Heroku
```

To open the app in your browser, type-

```
heroku open.
```

___

#<center>**Deploy NodeJS on AWS**</center>

![AWS](https://dev-to-uploads.s3.amazonaws.com/i/ijj66b9ylg4il6ubmf48.jpg)

As a very first step, We need to create a EC2 instance on the AWS, with **Amazon Linux 2** as the OS of choice for your server, and ssh into it .

After successful ssh into the EC2 instance , we need to follow the following steps to successfully deploy the NodeJS application.

1. Install NodeJS and NPM
2. Install Git and clone the repository with your project files.
3. Install all the dependencies
4. Install pm2 to run the server as a background process
configure the security group for the Ec2 instance

###**Step 1 – Install NodeJS and NPM**

Install NVM (Node Version Manager) by running the following command.

```terminal
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.34.0/install.sh | bash
```

Activate nvm by typing the following at the command line

```bash
. ~/.nvm/nvm.sh
```

Use nvm to install the latest version of NodeJS by typing the following at the command line.

```
nvm install node
```
Installing NodeJS also installs the Node Package Manager (NPM) so you can install additional modules as needed.

Test that NodeJS is installed and running correctly by typing the following at the command line.

```
node -v
```

```
npm -v
```

###**Step 2 – Installing Git and cloning the repository**

To install Git , run the following command in the terminal

```
sudo yum install git
```

To verify whether Git was installed properly in the system or not run the following command.

```
git –version
```

Run the following command to clone the repository

```
git clone <repository link>
```

###**Step 3 – Installing the dependencies**

change the directory to the cloned repo folder and run the following command.


```
npm install
```

###**Step 4 – Installing PM2 and starting the server**

PM2 is a daemon process manager that will help you manage and keep your application online.

Getting started with PM2 is straightforward, it is offered as a simple and intuitive CLI, installable via NPM.

>A daemon (pronounced DEE-muhn) is a program that runs continuously and exists for the purpose of handling periodic service requests that a computer system expects to receive. The daemon program forwards the requests to other programs (or processes) as appropriate. 

~ ***WhatIS.com***

A Daemon process is a program which runs as a background process, without the need of user interaction via terminal or a GUI. Running the node app as a daemon process enables you to access and execute other processes from your SSH session on your server, without which your node process will take up your current session's terminal.

To install pm2 run the following command.

```
sudo npm install pm2 -g
```

To start the server run:

```
sudo pm2 start build/index.js
```

To delete a pm2 process run

```
sudo pm2 delete <index no of the process>
```

###**Step 5 - Configure Security groups**

By default, nobody can access the application without configuring the Inbound traffic configurations for the EC2 instance.

***Quick explanation***

*The external IP dedicated to your EC2, only looks for SSH requests by default. Normal webpages, and REST APIs, mostly use the TCP protocol for data transfer. To make sure your server is secure and is not vulnerable to DDoS attacks (Distributed Denial Of Service), and to make sure that your assets and data remains secure.*

*To make sure that front-end applications can send requests and receive responses from our NodeJS application, we will need to expose the port to incoming TCP connections by changing the security settings for our EC2 instance.*

To configure Inbound traffic for the EC2 instance, follow the below steps:

1. Select the EC2 Instance and click on the security group link in the Description section.

2. By clicking the security group it will open the Security Group section. Here, we can configure Inbound and Outbound traffic properties. To make our application accessible from anywhere, click on the Inbound tab.

3. By clicking on the Edit button available in the Inbound tab, it will open Edit Inbound rules popup. By default, it will show SSH configurations.

<b>Since our application is configured for port number as your required port, we need to add a new rule “Custom TCP Rule”.</b>

Enter port range as your required port and select Source as “Anywhere”. After saving the changed rules, it will allow us to access our application from anywhere.

***That's it, folks!🎊 You've learnt successfully how to deploy your NodeJS application to production!***

**************
__We hope you found this insightful.__
Do visit our [website](https://nitdgplug.org/) to know more about us and also follow us on :
* [Facebook](https://www.facebook.com/nitdgplug)
* [Instagram](https://www.instagram.com/nitdgplug/)
* [Linkedin](https://www.linkedin.com/company/lugnitdgp/)
* [YouTube](https://www.youtube.com/channel/UCYZPnN5vP5B1sINLLkI1aDA)

Also do not forget to like and comment.

Until then, 
__stay safe, and May the Source Be With You!__

![Star Wars Who?](https://dev-to-uploads.s3.amazonaws.com/i/cplzcsry6s5r8m1pale8.gif)

This article was co-written by 
{% user vrohan %}
###<center>AND</center>
{% user deadlycoder07 %}