ads

How to Deploy a Node.js Application on AWS EC2 Instance

 How to Deploy a Node.js Application on AWS EC2 Instance:

 

Deploying a Node.js application on an Amazon Web Services (AWS) EC2 instance is a powerful way to run scalable web applications in the cloud. In this article, we will walk through the entire process—from setting up the EC2 instance to deploying your Node.js project live.





A Step-by-Step Guide


Step 1: Launch an EC2 Instance

1. Log in to AWS Console  

   Go to the [AWS Management Console](https://aws.amazon.com/console/), and log in using your credentials.


2. Navigate to EC2 Dashboard  

   Once logged in, type "EC2" into the search bar and click on EC2 under "Services." This will bring you to the EC2 dashboard.


3. Launch a New EC2 Instance  

   - Click on "Launch Instance."

   - Choose the Amazon Machine Image (AMI). For Node.js applications, the Ubuntu or Amazon Linux 2 AMI is recommended.

   - Select an instance type. The t2.micro is suitable for small applications and is part of the free tier.

   - Configure instance settings, like security groups, to allow SSH (port 22) and HTTP (port 80).


4. Create a Key Pair  

   When launching the instance, you’ll be asked to either create a new key pair or use an existing one. The key pair will be used to SSH into your instance, so make sure to save the `.pem` file.


5. Launch the Instance  

   Review the settings, and click 'Launch' . Your EC2 instance will be up and running in a few minutes.


 Step 2: Connect to Your EC2 Instance


1. **Find the Public IP**  

   Once the instance is running, go to the EC2 dashboard, click on your instance, and find the **Public IP Address**.


2. **Connect via SSH**  

   Open your terminal or SSH client, and connect to the instance using the command:   



ssh -i /path/to/key.pem ubuntu@your-ec2-ip-address

   

   Replace `/path/to/key.pem` with the actual path to your key file, and replace `your-ec2-ip-address` with your instance's public IP.


3. Update and Upgrade Packages  

   After logging into the EC2 instance, update the package list and upgrade the system by running:



sudo apt update

sudo apt upgrade -y



 Step 3: Install Node.js and NPM


1. **Install Node.js  

   AWS EC2 instances don't have Node.js pre-installed, so you need to install it:


curl -fsSL https://deb.nodesource.com/setup_16.x | sudo -E bash -

sudo apt-get install -y nodejs

   You can check the installation by verifying the Node.js and npm versions:



node -v

npm -v


 Step 4: Transfer Your Node.js Project to EC2


1. Initialize npm 


npm init


npm init

npm WARN config global `--global`, `--local` are deprecated. Use `--location=global` instead.

This utility will walk you through creating a package.json file.

It only covers the most common items, and tries to guess sensible defaults.


See `npm help init` for definitive documentation on these fields

and exactly what they do.


Use `npm install <pkg>` afterwards to install a package and

save it as a dependency in the package.json file.


Press ^C at any time to quit.

package name: (node)

version: (1.0.0)                                                                                                                            

description:                                                                                                                                

entry point: (index.js)                                                                                                                     

test command:                                                                                                                               

git repository:                                                                                                                             

keywords:                                                                                                                                   

author: codewithVDK                                                                                                                         

license: (ISC)                                                                                                                              


Json file

{

  "name": "node",

  "version": "1.0.0",

  "description": "",

  "main": "index.js",

  "scripts": {

    "test": "echo \"Error: no test specified\" && exit 1"

  },

  "author": "codewithVDK",

  "license": "ISC"

}


2. index.js file  

   To open the index.js file use the following command


vi index.js

code :


const http = require('http');
const fs = require('fs');
const url = require('url');

// Create an HTTP server
http.createServer((req, res) => {
    // Parse the URL to get the file name
    const queryObject = url.parse(req.url, true).query;
    const fileName = queryObject.file;

    if (!fileName) {
        res.writeHead(400, { 'Content-Type': 'text/plain' });
        res.end('Please provide a file name in the URL query string, e.g.,
?file=example.txt');
        return;
    }

    // Read the file
    fs.readFile(fileName, 'utf8', (err, data) => {
        if (err) {
            res.writeHead(404, { 'Content-Type': 'text/plain' });
            res.end('File not found or an error occurred while reading the
                    file.');
            return;
        }

        // Send the file content as the response
        res.writeHead(200, { 'Content-Type': 'text/plain' });
        res.end(data);
    });
}).listen(3000, () => {
    console.log('Server running at http://localhost:3000/');
});


 Step 5: Configure Security Group for HTTP Access


To allow external access to your Node.js app, ensure that your EC2 instance's security group allows traffic on HTTP (port 80).


1. Go to the Security Groups tab in your EC2 dashboard.

2. Select the security group attached to your instance.

3. Click on Edit Inbound Rules and add a new rule to allow HTTP traffic on port 80.

4. Save the changes.


 Step 6: Run the Node.js Application


Now, you can run your Node.js application. Start it using the following command:



node index.js

Replace `index.js` with the entry point of your Node.js application.


 Step 7: Access Your Node.js App


If everything is set up correctly, you should now be able to access your Node.js app via your EC2 instance's public IP or domain name.


Simply enter `http://your-ec2-ip-address:3000` in a browser, and your Node.js app should be live!


To run the above file : 3.7.71.131:3000/?file=example.txt 




Thank you...


-Code With VDK

Tags

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.

#buttons=(Ok, Go it!) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Ok, Go it!