Hosting a Node.js Express Project on AWS EC2 with Nginx

In this guide, we will walk through the process of hosting a Node.js Express project on an AWS EC2 instance using Nginx as a reverse proxy. If you need guidance on setting up an EC2 instance, check out our separate guide here: How to Create an AWS EC2 Instance.

Step 1: Create a Node.js Express Project

1. Initialize a New Project

First, create a new Node.js Express project locally:

npm init -y

2. Install Dependencies

Install the necessary packages:

npm install express cors nodemon

3. Create a server.js File

Now, create a server.js file in your project directory and add the following code:

  const express = require("express");
  const cors = require("cors");

  const app = express();
  const port = 3000;

  // Middleware
  app.use(express.json());
  app.use(cors());

  // Sample API Route
  app.get("/api/test", (req, res) => {
    res.json({ message: "Test API is working!" });
  });

  // Start Server
  app.listen(port, () => {
    console.log(`Server running on http://localhost:${port}`);
  });
  

4. Run the Server

Start the server using:

npm start

Now, open a browser and go to http://localhost:3000/api/test to see the API response.



Step 2: Upload Project to GitHub

Since we will deploy this project on AWS, upload all files (except node_modules) to a GitHub repository.

Step 3: Connect to AWS EC2 via SSH


After setting up your EC2 instance, connect to it using SSH:

ssh -i your-key.pem ubuntu@your-ec2-public-ip

Step 4: Install Node.js and Git on EC2


1. Update the System

sudo apt update

2. Install Git

sudo apt install git -y

Verify the installation:

git --version

3. Clone the GitHub Repository

Create a directory and clone your project:

mkdir project-folder
cd project-folder
git clone https://github.com/your-username/your-repository.git


Then, navigate into the cloned repository:

cd your-repository

4. Install Node.js

Install the latest Node.js version:

curl -fsSL https://deb.nodesource.com/setup_current.x | sudo -E bash -
sudo apt-get install nodejs -y

Verify installation:

node -v
npm -v


5. Install Dependencies and Start the Server

npm install
npm start

At this point, the project is running, but we need a better way to keep it running in the background.


Step 5: Use PM2 for Process Management

PM2 ensures that our Node.js application remains active even after a reboot.

1. Install PM2
sudo npm install -g pm2
2. Start the Application with PM2
pm2 start server.js --name my-app
3. Set PM2 to Start on Reboot

pm2 startup
pm2 save
You can check the status of running applications:
pm2 list
pm2 logs

Step 6: Configure Nginx as a Reverse Proxy


Nginx allows us to access our application via a public domain or IP without specifying a port.

1. Install Nginx

sudo apt-get install -y nginx
2. Configure Security Group

  • Go to AWS EC2 Dashboard > Security Groups.
  • Edit the Inbound Rules and add a new rule:
    • Type: HTTP
    • Source: Anywhere (0.0.0.0/0, ::/0)
  • Save the changes.


Now, enter your EC2 public IP in a browser:

http://your-public-ip
You should see the Nginx default welcome page.

3. Update Nginx Configuration

Navigate to the Nginx configuration directory:

cd /etc/nginx/sites-available

List the files to ensure default exists:
ls

Edit the default configuration file:

sudo nano default

Modify the file to add a proxy configuration for our Node.js app:

server {
    
    listen 80;
    server_name your-public-ip;
    
    location /api { 
    	rewrite ^/api/(.*)$ /$1 break;
	proxy_pass http://localhost:3000;
	proxy_set_header Host $host;
    	proxy_set_header X-Real-IP $remote_addr;
    	proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}


Save and exit (CTRL + X, then Y, then Enter).

4. Restart Nginx

sudo systemctl restart nginx

Check the status:

sudo systemctl status nginx


5. Verify API Access

Now, test your API in the browser:

http://your-public-ip/api/test

If everything is set up correctly, you should see:

{ "message": "Test API is working!" }

Post a Comment

0 Comments