How To Deploy Nodejs App To Heroku In 10 Steps


Step 1: 

 Create a Heroku account (click here) and also install Heroku CLI  (click here) in your local pc.


Step 2: 

    Make sure Node.js (click here) and Git (click here) installed in your local pc.

  •  To check git version 

git --version  

  • To check node version 

node -v         


Step 3:  

     To create (or) import a node repo.

  • For creating a new repo.  

    • Create a folder mkdir folder-name and move to that folder cd folder-name.

    • Initialize the git using git init command.

    • Initialize the node project npm init --y. It creates the default project details.

    • Make changes in the project as per requirement.

  • Import existing git repo.

git clone project_ssh_url



Step 4: 

Update your package.json file with include start script, main and engines.

# package.json

{
name: “application-name”,

version: “0.0.1”,

main: “app.js”,

script: {

   start: “node app.js”

},

engines:{

   node: “8.4.0”

}

}


Step 5:

Now in your root directory create a new file with name Procfile Make sure P in Procfile is capital letter and file should not have any extension.


echo "web: node app.js" > Procfile


Note: I have used app.js as a filename. Change filename accordingly.


Step 6:

Check process.env.PORT at app listener.

app.listen(process.env.PORT || 3000)


Step 7:

Login in to heroku using CLI command.

heroku login


Follow the prompts to enter your heroku login credentials


Step 8:

Create a heroku project using heroku create command.

heroku create


Note: It will create a project with a random name.


Create a project with a specific name

heroku create <your app name>


Above step will create a project repo where you can push your changes.


Step 9:

  • Run below command to set remote repo for your heroku app.


git remote -v


  • This command will add all file changes to the stage.


git commit -am “your message”


  • This command will push all stage changes to heroku server.


git push heroku master



That's all your app will be deployed.



Step 10:


heroku open


            It will open your application in the default browser.



Some useful Heroku commands

  • Set Environment variables:

Run below command to set an environment variable.

heroku config:set NODE_ENV=Development


  • Troubleshooting 

To check application logs

heroku logs --tail


For more commands ( click here ). Please comment below for any suggestion.