OneCompiler

Deploying node application to Heroku server

334

In this post, I am going to explain how to deploy node application in Heroku server. To getting started with Heroku we should follow two steps

  • First we need to create Heroku account it's free and easy to create

  • Next we need to install Heroku CLI

To install Heroku in Ubuntu run the following in your terminal.

$ sudo snap install --classic heroku

https://devcenter.heroku.com/articles/heroku-cli

Follow the above link to install Heroku CLI in windows and MAC OS.

Command to check Heroku CLI is installed or not is

$ heroku -v

The command to login into the Heroku is

$ heroku login

Enter your credentials once you type the above command.

We need to modify our package.json file before deploying our code into Heroku.

{
  "name": "",
  "description": "",
  "version": "0.0.1",
  "author": "",
  "license": "ISC",
  "engines": {
    "node": ">=8.0.0"
  },
  "scripts": {
    "start": "node index.js"
  },
  "dependencies": {
    "body-parser": "^1.17.2",
    "co": "^4.6.0",
    "connect": "^3.6.6",
    "cookie-parser": "^1.4.3",
    "ejs": "^2.5.6",
    "elasticsearch": "^14.1.0",
    "events": "^3.0.0",
    "express": "^4.16.2"
  }
}

To run our application using npm we need to define it in scripts. In above package.json file we can start our application using npm start command.

Note: When we deploy the application in Heroku it will run our application using npm start command.

Before creating/deploying our application in Heroku we need to commit our changes in our local repository.

**Steps to create & commit our changes in local repo **

$ git init
 
// The above command will create a repository in local repository

$ git add .

// To add our changes in files

$ git commit -m "message"

** Deploying to Heroku: **

Once we complete creating a repository then we can use Heroku CLI to deploy our source code in Heroku.


$ heroku create Application name

// Application name should be unique and it is optional if we left blank Heroku will assign a default name.

The create command will do two things

  • It creates an application in Heroku
  • It creates git remote in our local git environment

Whenever we have any changes there in our source code we will commit them to our local repository later we push them to the remote repository which is available in Heroku.

Heroku will pull the changes from the remote repository.

Command to see the list of remote repositories in git is

$ git remote -v

// This will show available remote repositories

Now we can deploy our application with one command

$ git push heroku master

There are two options available to view logs in Heroku

  • Using Heroku CLI
  • Heroku dashboard

Heroku CLI:

$ heroku logs

// This command will display all logs of your application

In this way, we deploy our application in Heroku server