Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • NodeJS Tutorial
  • NodeJS Exercises
  • NodeJS Assert
  • NodeJS Buffer
  • NodeJS Console
  • NodeJS Crypto
  • NodeJS DNS
  • NodeJS File System
  • NodeJS Globals
  • NodeJS HTTP
  • NodeJS HTTP2
  • NodeJS OS
  • NodeJS Path
  • NodeJS Process
  • NodeJS Query String
  • NodeJS Stream
  • NodeJS String Decoder
  • NodeJS Timers
  • NodeJS URL
  • NodeJS Interview Questions
  • NodeJS Questions
  • Web Technology
Open In App
Next Article:
Deploying Node.js Applications
Next article icon

Deploying Node.js Applications

Last Updated : 07 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Deploying a NodeJS application can be a smooth process with the right tools and strategies. This article will guide you through the basics of deploying NodeJS applications.

To show how to deploy a NodeJS app, we are first going to create a sample application for a better understanding of the process. 

Steps to Create a Node Application

Step 1: Create a project folder.

mkdir example

Step 2: Initialize the node application

npm init -y

Folder Structure

wqefg
Folder Structure

Step 3: Create the files as shown in the folder structure and add the following codes.

HTML
<!-- head.html -->  <!DOCTYPE html> <html>  <head>     <title>Hello World</title> </head>  <body>      <h1>This is the Homepage</h1>      <p><a href="/tailPage">Go to Next Page</a></p>   </body>  </html> 
HTML
<!-- tail.html -->  <!DOCTYPE html> <html>  <head>     <title>Hello World</title> </head>  <body>      <h1>WORKING</h1>  </body>  </html> 
JavaScript
//app.js  var http = require('http'); var fs = require('fs'); // to get data from html file  http.createServer(function (req, res) {     var url = req.url;     if (url === "/") {         fs.readFile("head.html", function (err, pgres) {             if (err) {                 res.writeHead(404, { 'Content-Type': 'text/plain' });                 res.write("HEAD.HTML NOT FOUND");                 res.end();             } else {                 res.writeHead(200, { 'Content-Type': 'text/html' });                 res.write(pgres);                 res.end();             }         });     } else if (url === "/tailPage") {         fs.readFile("tail.html", function (err, pgres) {             if (err) {                 res.writeHead(404, { 'Content-Type': 'text/plain' });                 res.write("TAIL.HTML NOT FOUND");                 res.end();             } else {                 res.writeHead(200, { 'Content-Type': 'text/html' });                 res.write(pgres);                 res.end();             }         });     }  }).listen(3000, function () {     console.log("SERVER STARTED PORT: 3000"); }); 


Step 4: Open the terminal and write the following command to run the server 

node app.js 


To see your application running, type "localhost:3000" in your browser as URL. We have successfully created the sample application, we are now going to deploy it on the web. There's are many cloud platforms like AWS, Heroku, Digital Ocean, etc.

Steps to Deploy Sample Application

For this example, we are going to use Heroku since it's easy to use and you can use it to test your apps for free.

NOTE: ALL THE COMMAND ARE PERFORMED INSIDE THE DIRECTORY/FOLDER WHICH CONTAINS YOUR PROJECT

Step 1: Go to https://www.heroku.com/ and register.

Step 2: After completing the registration process, login and go to https://dashboard.heroku.com/apps

Before Proceeding any further, make sure you have installed the latest version of Git on your PC.

Step 3: Go to Getting Started on Heroku with Node.js and download the Heroku Cli for your system.
You can check if Heroku CLI is successfully installed or not by typing the command. 

heroku -v

It should look like this


Step 4: Login to heroku using the command line

heroku login 

Press any key to continue, it will open a new tab in your browser asking you to login in your Heroku account.

Click on Log in Bottom. After you successfully log in, the command line will look like this

( Heroku might not connect to Git bash, so use Command Prompt or terminal if it's taking very long to connect i.e. if you were using git bash.

Step 5: Now, make sure we are using Git in the top level directory of our app. We can check if the directory have Git or not by the command. 

git status

To make it a git directory, type the command 

git init 

Now,  add and save all the changes using the command.

git add .  

Now, we need to commit the files we have added to git. Type 

git commit -m "initial commit"

Step 6: Create heruko app by command 

heroku create

This will create a git remote which is connected to our local git repository

Step 7: Run the following command to deploy the app on heroku server. 

git push heroku master

Step 8: After deploying the app run the following command to make sure one instance of app is running. 

heroku ps:scale web=1 

Step 9: Run the following command to open the app in your browser.

heroku open 

Now, you might be getting a screen like this
 


Go to command line and run the following command to check for error. It helps to debug the application.

heroku logs  


It says "npm ERR! missing script: start". To fix this problem, we need to set up a start script, the start script tells the server to run "node app.js" after installing the packages.

Step 10: To setup the start script, open package.json inside the example folder and type "start": "node app.js" inside the "scripts" tag.  

Step 11: Type the following command in command line We need to push the app to Heroku every time we make changes in it.

git add .
git commit -m "another commit"
git push heroku master
heroku open


Step 12: There's still a problem. The problem is still not fixed. We are using PORT: 3000 but Heroku doesn't. Heroku uses a dynamic port, we cannot fix it to 3000. If we want our application to work on Heroku we need to add the following line in the app.js file

.listen(process.env.PORT || 3000, function(...));
JavaScript
// app.js  var http = require('http'); var fs = require('fs');   http.createServer(function (req, res) {      var url = req.url;     if (url === "/") {         fs.readFile("head.html", function (err, pgres) {             if (err)                 res.write("HEAD.HTML NOT FOUND");             else {                 res.writeHead(200, { 'Content-Type': 'text/html' });                 res.write(pgres);                 res.end();             }         });     }     else if (url === "/tailPage") {         fs.readFile("tail.html", function (err, pgres) {             if (err)                 res.write("TAIL.HTML NOT FOUND");             else {                 res.writeHead(200, { 'Content-Type': 'text/html' });                 res.write(pgres);                 res.end();             }         });     }  }).listen(process.env.PORT || 3000, function () {     console.log("SERVER STARTED PORT: 3000"); });  

Step 13: Again run the following command.

git add .
git commit -m "another commit"
git push heroku master
heroku open

Output

Congratulations, you have successfully deployed your first web application.

Note: If your application uses MongoDB then you will have to deploy MongoDB server separately on some other cloud platform. 


Next Article
Deploying Node.js Applications

A

Archaic
Improve
Article Tags :
  • Web Technologies
  • Node.js
  • Hosting

Similar Reads

    Deploying A Node.js Application In kubernetes
    Kubernetes, or K8s, is an open-sourced container orchestration technology that is used to automate the manual processes of deploying, managing, and scaling applications with the help of containers. Kubernetes was originally developed by engineers at Google, and In 2015, it was donated to CNCF (Cloud
    9 min read
    Deploy a Node.js Application with Azure
    Deploying a Node.js application on Azure, a prominent cloud computing platform, has become a seamless process, thanks to its user-friendly interface and integration capabilities. This guide aims to walk you through deploying a Node.js application on Azure using the Azure portal. We will cover essent
    4 min read
    Node First Application
    NodeJS is widely used for building scalable and high-performance applications, particularly for server-side development. It is commonly employed for web servers, APIs, real-time applications, and microservices.Perfect for handling concurrent requests due to its non-blocking I/O model.Used in buildin
    4 min read
    How to Deploy Node.js Application in Kubernetes?
    Deploying the Node.js application on Kubernetes in a containerized manner makes it highly scalable,fault-tolerant, and allows for zero downtime. Kubernetes allows container orchestration that can be used in many ways during deployment. Load balancing is provided, which helps with automatic load tran
    4 min read
    How To Deploy Node Js Application In AWS Lightsail ?
    Lightsail can be defined as a simple, easy-to-use, and user-friendly service offered by Amazon Web Services (AWS). The main goal of Lightsail is to provide an easy way for individuals, startups, and small businesses to launch and manage virtual private servers (VPS) and other cloud services without
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences