Install Node.js on EC2

Welcome to our guide on how to install Node.js on an Amazon EC2 instance. Node.js is a powerful and popular JavaScript runtime built on Chrome’s V8 JavaScript engine. It is known for its efficiency, non-blocking I/O model, and wide usage in building scalable network applications. This guide aims to walk you through setting up Node.js in a robust and secure environment provided by Amazon’s Elastic Compute Cloud (EC2).

Amazon EC2 offers resizable computing capacity in the cloud, making web-scale computing easier for developers. With EC2, you can launch virtual servers, configure security and networking, and manage storage. It provides a reliable environment for deploying applications like Node.js, allowing you to choose the instance type that best fits your application’s needs.

Whether you are a beginner looking to host your first Node.js application or an experienced developer seeking to leverage the power of AWS, this guide is designed for you. We will cover everything from the initial setup of an EC2 instance to deploying a Node.js application.


Before diving into the installation process, there are a few prerequisites you need to ensure are in place:

  • AWS Account: You need an active Amazon Web Services (AWS) account. If you don’t have one, you can sign up for a free tier account that provides limited access to many AWS services, including EC2.
  • EC2 Instance: Set up an EC2 instance where Node.js will be installed. If you are new to this, AWS provides a straightforward process to launch a new instance, where you can choose the operating system (like Ubuntu, Amazon Linux, etc.) and instance type based on your requirements.
  • Basic Linux Knowledge: Basic familiarity with Linux commands is required if you are using a Linux-based instance. This includes knowledge of how to connect to the instance via SSH, navigating the file system, and executing basic commands.
  • SSH Key Pair: For secure access to your EC2 instance, you’ll need an SSH key pair. AWS allows you to create a new key pair or use an existing one during the instance creation process.

Choosing the Right EC2 Instance

Selecting the appropriate EC2 instance type is crucial for the performance and cost-effectiveness of your Node.js application. Here are some factors to consider:

  • Instance Type: AWS offers a variety of instance types that cater to different use cases. For Node.js applications, you generally need a balance between CPU, memory, and network performance. Instance types like t2.micro or t3.micro are often sufficient for small to medium applications, especially if you’re just starting out or running non-resource-intensive applications.
  • Operating System: Choose an operating system that you are comfortable with and that supports Node.js. Popular choices include Ubuntu, Amazon Linux, and CentOS. Each has its strengths and the choice often depends on your familiarity and the specific needs of your application.
  • Scalability: Consider future scalability needs. AWS EC2 provides the flexibility to scale your instances vertically (upgrading to a higher capacity instance) and horizontally (adding more instances). Understanding your application’s growth can guide you in choosing an instance that won’t require frequent changes.
  • Cost Considerations: Be mindful of the costs associated with the chosen instance type. The AWS free tier offers certain instances (like t2.micro) for free for the first year, but beyond that, or if you choose a different instance type, charges will apply.
  • Region Selection: Choose an AWS region closer to your target audience for reduced latency and faster response times.

Connecting to Your EC2 Instance

Once your EC2 instance is up and running, the next step is to connect to it. This is typically done via Secure Shell (SSH), a protocol for securely accessing remote machines over a network.

  • Locate Your Public DNS: In your AWS EC2 dashboard, find the public DNS (Domain Name System) of your instance. This information is used to establish the SSH connection.
  • SSH Key Pair: Ensure you have the private key file (.pem file) that you created or selected when launching the instance. This key is crucial for secure access.
  • Connecting via SSH: The exact command to connect will depend on your operating system and the type of instance you’ve launched. A typical SSH connection command looks like this:
  • ssh -i /path/to/your-key.pem ec2-user@your-instance-public-dns
  • Replace /path/to/your-key.pem with the path to your private key file and your-instance-public-dns with your instance’s public DNS.
  • Security Group Settings: Ensure your instance’s security group has an SSH rule that allows connections from your IP address.
  • Troubleshooting: If you encounter issues, verify your key’s permissions, check the instance’s security group rules, and ensure your internet connection is stable.

Once connected, you are ready to start the installation of Node.js on your EC2 instance.

Installing Node.js on EC2

Installing Node.js on your EC2 instance involves a few straightforward steps. You can use Node Version Manager (NVM) for this purpose as it allows you to install multiple Node.js versions and switch between them if needed.

  • Update Your Instance: Before installing anything, it’s a good practice to update your package manager. On Ubuntu, you would run:
sudo apt update && sudo apt upgrade

Install NVM: To install NVM, you can use the following curl command:

curl -o- | bash
  • This command fetches and executes the NVM installation script.
  • Activate NVM: After installing, load NVM into your current session:
source ~/.bashrc

Install Node.js: Now, install Node.js using NVM. For the latest version, use:

nvm install node
  • To install a specific version, replace node it with the version number, like nvm install 14.17.0.
  • Verify Installation: Confirm the installation of Node.js and npm (Node Package Manager) by checking their versions:
node -v
npm -v

Configuring the Environment

After successfully installing Node.js, you might need to configure your environment for your application.

  • Environment Variables: Set any necessary environment variables. You can add these to your ~/.bashrc or ~/.bash_profile file for persistence. For example:
export DB_HOST=localhost
export DB_USER=root
  • Firewall Configuration: Modify your security group rules to allow traffic to your Node.js application. Typically, Node.js apps run on port 3000, so you might need to allow traffic on this port.
  • Security Groups: Access your EC2 dashboard, go to ‘Security Groups’, select your instance’s security group, and edit inbound rules to add a custom TCP rule for the port your Node.js app uses.
  • Testing the Setup: To test your setup, you might want to run a simple Node.js “Hello World” application and check if it’s accessible from the browser.

This configuration ensures your Node.js environment is correctly set up and ready for deploying applications.

Deploying a Sample Node.js Application

Now that Node.js is installed and your environment is set up, let’s deploy a simple Node.js application to ensure everything is working correctly.

  • Create a Sample App: In your EC2 instance, create a new directory for your application, and initialize a new Node.js project:
mkdir myapp
cd myapp
npm init -y

Simple Application Code: Create an index.js file with a basic HTTP server that listens on a port (e.g., 3000):

const http = require('http');
const port = 3000;
const server = http.createServer((req, res) => {
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/plain');
    res.end('Hello World\n');
server.listen(port, () => {
    console.log(`Server running at port ${port}`);

Run the Application: Start your application by running:

node index.js
  • Access the Application: Open a web browser and access your application using your EC2 instance’s public IP or DNS followed by the port number (e.g., http://ec2-instance-public-dns:3000). You should see the “Hello World” message.
  • Troubleshooting: If you can’t access your application, check your EC2 instance’s security group settings and ensure the correct ports are open.

Securing Your Node.js Application on EC2

Security is paramount, especially when deploying applications in the cloud. Here are some steps to secure your Node.js application on EC2:

  • Use a Reverse Proxy: Implement a reverse proxy like Nginx to handle incoming HTTP requests. This adds a layer of abstraction and control to enhance security and performance.
  • Implement HTTPS: Secure your application by setting up an SSL/TLS certificate. Services like Let’s Encrypt offer free certificates. Redirect all HTTP traffic to HTTPS.
  • Keep Software Updated: Regularly update your operating system and Node.js to their latest versions to ensure you have the latest security patches.
  • Use Environment Variables for Sensitive Data: Store sensitive information like database credentials in environment variables instead of hardcoding them in your application.
  • Regular Backups: Ensure regular backups of your application and databases to recover quickly in case of data loss.

Performance Monitoring and Management

Monitoring the performance of your Node.js application is crucial for maintaining its health and responsiveness.

  • Utilize CloudWatch: AWS CloudWatch provides monitoring and logging services. It can track metrics, collect log files, set alarms, and automatically react to changes in your AWS resources.
  • Application Performance Monitoring (APM) Tools: Consider using APM tools like New Relic or Datadog, which offer insights into your application’s performance and help identify bottlenecks.
  • Load Balancing: For high-traffic applications, use Elastic Load Balancing (ELB) to distribute incoming application traffic across multiple instances, improving scalability and fault tolerance.
  • Auto-Scaling: Implement auto-scaling to automatically adjust the number of EC2 instances based on the demand. This ensures that your application maintains steady, predictable performance at the lowest possible cost.
  • Optimize Code and Database Queries: Regularly review and optimize your Node.js code and database queries for performance improvements.

Updating and Maintaining Node.js on EC2

Regular maintenance is essential for the smooth operation of your Node.js application on EC2. Here’s how you can keep everything up-to-date:

  • Update Node.js: If you’re using NVM (Node Version Manager), updating Node.js is straightforward. Simply use the command nvm install node to install the latest version of Node.js. You can also specify a specific version if needed.
  • Managing Dependencies: Regularly update your application’s dependencies. Use npm outdated to check for outdated packages and npm update to update them.
  • System Updates: Keep your EC2 instance’s operating system updated. For most Linux distributions, this can be done using package managers like apt or yum with commands like sudo apt update && sudo apt upgrade.
  • Monitoring Logs: Regularly check application and system logs to identify and resolve issues. AWS CloudWatch can be configured to monitor and alert you about specific log patterns.
  • Backup Strategy: Implement a robust backup strategy for your application data and code. AWS offers services like S3 and EBS snapshots for backups.


Congratulations on setting up and deploying your Node.js application on an Amazon EC2 instance! You’ve gone through the steps of setting up an EC2 instance, installing Node.js, deploying a sample application, securing your setup, and ensuring your application’s performance and maintenance.

This guide aims to provide a comprehensive overview of the process, but the journey doesn’t end here. The world of AWS and Node.js is vast, with numerous advanced topics and best practices to explore. We encourage you to continue learning and experimenting.

If you have any feedback, questions, or suggestions, please feel free to reach out. Your input is invaluable in helping us improve and provide more useful content.

Frequently Asked Questions (FAQ)

Q1: Can I host multiple Node.js applications on a single EC2 instance?

  • A1: Yes, you can host multiple Node.js applications on a single EC2 instance. However, manage resources and ports carefully to ensure that applications do not interfere with each other.

Q2: How do I handle traffic spikes in my Node.js application?

  • A2: Use AWS Auto Scaling and Elastic Load Balancing to handle traffic spikes. These services automatically adjust the number of EC2 instances based on the demand.

Q3: What should I do if my Node.js application crashes?

  • A3: Investigate the logs to understand the cause. Consider using a process manager like PM2 to automatically restart your Node.js application if it crashes.

Q4: How can I secure sensitive data like database credentials in my application?

  • A4: Store sensitive data in environment variables or use AWS Secrets Manager to manage, retrieve, and rotate credentials securely.

Q5: Are there cost-effective strategies for running a Node.js app on EC2?

  • A5: Opt for reserved instances if you have predictable usage, use spot instances for non-critical or flexible workloads, and continuously monitor your usage to optimize costs.

Atiqur Rahman

I am MD. Atiqur Rahman graduated from BUET and is an AWS-certified solutions architect. I have successfully achieved 6 certifications from AWS including Cloud Practitioner, Solutions Architect, SysOps Administrator, and Developer Associate. I have more than 8 years of working experience as a DevOps engineer designing complex SAAS applications.

Leave a Reply