Front-end Tutorials

Front-end Tutorials

HTMLCSSSassJavaScriptReactJS
CMS Tutorials

CMS Tutorials

WordPress
Tutorials expand

Deploy Node.js Website on an EC2 Instance

Posted in AWS Tutorial
Updated on Sep 22, 2024
By Mari Selvan
👁️ 73 - Views
⏳ 4 mins
💬 1 Comment
Deploy Node.js Website on an EC2 Instance

Photo Credit to CodeToFun

🙋 Introduction

In the vast landscape of web development, deploying a Node.js website on a cloud server is a common and essential task.

Amazon Elastic Compute Cloud (EC2) provides a scalable cloud computing solution, allowing developers to easily deploy and manage applications.

In this tutorial, we'll walk through the steps of deploying a Node.js website on an EC2 instance.

📚 Prerequisites

Before we begin, make sure you have the following prerequisites:

  1. AWS Account and EC2 Access:

    Ensure you have an AWS account with access to the EC2 service.

  2. Running EC2 Instance:

    Make sure you have an EC2 instance that is up and running.

  3. Elastic IP Association:

    Associate an Elastic IP with your EC2 instance to provide a static IP address.

  4. File Transfer with Filezilla:

    Set up Filezilla with a connection to your EC2 instance for easy file transfer.

  5. Secure Shell Access with PuTTY:

    Configure PuTTY to establish a secure shell connection to your EC2 instance.

  6. Node.js and NPM Installation:

    Ensure Node.js and NPM are installed on your EC2 instance for running your Node.js application.

🖥️ Creating a Simple Node.js App

Let's develop a straightforward Node.js web application that comprises two files: the index.js, and a hello-world.html files.

Here the index.js is the core node.js file

index.js
Copied
Copy To Clipboard
const http = require('http');
const fs = require('fs');
const path = require('path');

const server = http.createServer((req, res) => {
  // Handling the root ("/") route
  if (req.url === '/') {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('Hello, this is the root!');
  }

  // Handling the "/hello-word" route
  else if (req.url === '/hello-world') {
    const filePath = path.join(__dirname, 'hello.html');

    // Reading the HTML file
    fs.readFile(filePath, 'utf8', (err, data) => {
      if (err) {
        res.writeHead(500, { 'Content-Type': 'text/plain' });
        res.end('Internal Server Error');
      } else {
        res.writeHead(200, { 'Content-Type': 'text/html' });
        res.end(data);
      }
    });
  }

  // Handling other routes
  else {
    res.writeHead(404, { 'Content-Type': 'text/plain' });
    res.end('404 Not Found');
  }
});

const PORT = 80;

server.listen(PORT, () => {
  console.log(`Server running at http://localhost:${PORT}/`);
});

Create a sample page named hello-world.html, and utilize node.js to serve this page when a GET request for '/hello-world' is made.

Demo.java
Copied
Copy To Clipboard
<!DOCTYPE html>
  <html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Hello World</title>
  </head>
  <body>
    <h1>Hello, World!</h1>
    <p>This is the hello.html file served by Node.js.</p>
  </body>
  </html>

🚀 Launching an EC2 Instance

After completing the prerequisites, proceed with the following steps to deploy your Node.js application on an EC2 instance.

  1. Make sure that your EC2 instance is operational and running.

    EC2 is up and Running

    Photo Credit to CodeToFun

  2. Establish a connection to the EC2 instance using PuTTY.

    Putty login

    Photo Credit to CodeToFun

  3. Make sure that Node.js and npm are installed on your Amazon Ubuntu Instance.

    Verifying node.js and npm is installed

    Photo Credit to CodeToFun

  4. Create a directory on your Amazon Ubuntu EC2 instance with the provided command.

    sudo mkdir nodejs-website
    create folder

    Photo Credit to CodeToFun

  5. Grant permission to the directory to enable file uploads.

    Before granting permission, the directory name appears in blue color with transparent background.

    After granting permission, the directory name appears in blue color with green background.

    Run the following command to grant permission.

    sudo chmod 777 /home/ubuntu/nodejs-website
    Grant Permission to the folder

    Photo Credit to CodeToFun

  6. Transfer your website files and folders from your local machine to an EC2 instance using Filezilla.

    upload files from local to ec2 instance using filezilla

    Photo Credit to CodeToFun

  7. Next, use PuTTY to globally install PM2. Use the following command to install PM2.

    sudo npm i -g pm2
    Install PM2 globally

    Photo Credit to CodeToFun

  8. Navigate to the website directory and initiate the application with pm2 by executing the following command:

    sudo pm2 start index.js
    start application using pm2

    Photo Credit to CodeToFun

    Congratulations! We have successfully initiated our Node.js application using pm2. You can now close PuTTY.

  9. Proceed to step 1, where you should copy the Public IPv4 DNS or Public IPv4 address, then paste it into the URL and press Enter.

    node.js website running in ec2 instance

    Photo Credit to CodeToFun

    Our Node.js application is running successfully on our Amazon Ubuntu EC2 instance.

🎉 Conclusion

Congratulations! You've successfully deployed a Node.js website on an EC2 instance. Remember to monitor your application, set up security measures, and consider using a domain name for a production environment.

👨‍💻 Join our Community:

To get interesting news and instant updates on Front-End, Back-End, CMS and other Frameworks. Please Join the Telegram Channel:

Author

author
👋 Hey, I'm Mari Selvan

For over eight years, I worked as a full-stack web developer. Now, I have chosen my profession as a full-time blogger at codetofun.com.

Buy me a coffee to make codetofun.com free for everyone.

Buy me a Coffee

Share Your Findings to All

Subscribe
Notify of
guest
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Mari Selvan
Mari Selvan
9 months ago

If you have any doubts regarding this article (Deploy Node.js Website on an EC2 Instance), please comment here. I will help you immediately.

We make use of cookies to improve our user experience. By using this website, you agree with our Cookies Policy
AgreeCookie Policy