Node Js - Deploy your node project to the Heroku server

Node Js - Deploy your node project to the Heroku server

Heroku is a platform as service (PaaS) that enables developers to build, run and operate applications entirely in the cloud.

Steps to Deploy the node app to the Heroku cloud platform:

1. Create a Heroku account. It's free.

2. Install Heroku CLI globally

   To manage Heroku Cloud from your terminal, install Heroku CLI using the npm package.
 
    npm install -g heroku

   -g will install heroku globally.

3. Login to Heroku cloud platform

  Either open the Heroku.com and login there or you could also launch Heroku from your terminal using the command: heroku login
 
  This will launch the Heroku login page in the browser. Login with email and password used when creating your account. 


4. Add SSH public key installed in our system to Heroku

    Use the command: heroku keys:add

 
 
Note: Run the above command using node js command prompt, if it does not work with the Visual Studio code terminal.


5. Create a Heroku application on the cloud.

Choose a unique name for your project.


As you can see, when you create an app, you get the public URL for your app:

https://vishal007-myfirstnodeapp.herokuapp.com







6. Add an npm script in package.json file

    Heroku will use the npm script to start your project.



Heroku will run this "start" script using the command: npm run start


7. Change the Port on which your node server is running

 we specify the port in app.listen method where our node app will be running as shown in given code


app.listen(8000, () => {
  console.log("server is up and running at 8000 port");
});


But Heroku can not run on your local port. So we have to take the port dynamically what Heroku provides us.

process.env.PORT

app.js


const express = require("express");
const path = require("path");
const app = express();

const port  = process.env.PORT|| 8000

app.set("view engine", "hbs");

app.get("/", (req, res) => {
  res.render("index", { title: 'Template', message: 'Hello from Heroku' });
});

app.listen(port, () => {
  console.log("server is up and running on port"+ port);
});



index.hbs

<html>
    <head>
        <title>{{title}}</title>
    </head>
    <body>
        <h1>{{message}}</h1>
    </body>
</html>


8. Commit your changes and push to GitHub using "git push".

9. Push code to Heroku using the command:

   git push heroku master



If you face any error in deploying the code to Heroku, you can check logs using the command:

heroku logs -t




  








Post a Comment

0 Comments