Beginner’s Guide to Deploying a MERN Stack Project on Amazon EC2

Beginner’s Guide to Deploying a MERN Stack Project on Amazon EC2

·

5 min read

In this article, we’ll guide you through deploying a simple MERN stack application (MongoDB, Express, React, and Node.js) on an Amazon EC2 instance. This step-by-step guide will help beginners understand the process of getting a MERN stack application up and running in the cloud.


What is a MERN Stack?

The MERN stack is a set of technologies used to develop full-stack web applications. It consists of:

  • MongoDB: A NoSQL database that stores data in a flexible, JSON-like format.

  • Express: A Node.js web framework that helps in building the backend of the application.

  • React: A JavaScript library for building user interfaces, mainly for the frontend.

  • Node.js: A runtime environment that executes JavaScript code outside the browser, used to run your server.

What is EC2?

Amazon EC2 (Elastic Compute Cloud) is a service that allows you to run virtual servers in the cloud. These servers, also known as instances, can host your website or web application.


Prerequisites

Before you start, you’ll need the following:

  1. AWS Account: You can create one for free on the AWS website.

  2. Basic understanding of JavaScript, React, Node.js, and Express.

  3. A MERN stack application (or you can follow along with the example we’ll use).


Step-by-Step Guide

Step 1: Launching an EC2 Instance

  1. Log in to AWS Console:

    • Go to the AWS Console, and sign in with your AWS account credentials.
  2. Create a New EC2 Instance:

    • In the search bar, type “EC2” and click on it.

    • Click on the Launch Instance button to create a new EC2 instance.

    • Choose Ubuntu Server 20.04 LTS as the AMI (Amazon Machine Image), which is a popular choice for web servers.

    • Select the t2.micro instance type (this is free-tier eligible).

    • Create a new key pair, which you’ll use to SSH into your EC2 instance. Download the .pem file and keep it safe.

  3. Configure Security Group:

    • You need to open ports 22 (for SSH), 80 (for HTTP), and 443 (for HTTPS). This will allow you to access the EC2 instance and your application over the web.
  4. Launch Instance:

    • After configuration, click Launch. Once the instance is created, you’ll be able to see its public IP address.

Step 2: Connect to EC2 Instance

  1. SSH into EC2 Instance:

    • Open your terminal and navigate to the directory where your .pem file is located.

    • Use the following command to connect to your EC2 instance (replace with your actual .pem file and EC2 public IP):

        ssh -i your-key.pem ubuntu@your-ec2-public-ip
      
  2. Update Your Instance:

    • Once logged in, update the instance to ensure all packages are up to date:

        sudo apt update
        sudo apt upgrade
      

Step 3: Install Node.js, Nginx, and Git

  1. Install Node.js:

    • Use the following commands to install Node.js:

        curl -fsSL https://deb.nodesource.com/setup_16.x | sudo -E bash -
        sudo apt install -y nodejs
      
  2. Install Nginx (for serving your frontend and reverse proxy for backend):

     sudo apt install nginx
    
  3. Install Git (to clone your project from GitHub or other repositories):

     sudo apt install git
    

Step 4: Clone Your MERN Stack Project

  1. Clone Your Backend and Frontend Repositories:

    • Use Git to clone your backend and frontend repositories. Run the following commands (replace with your GitHub URLs):

        git clone https://github.com/your-username/your-backend-repo.git
        git clone https://github.com/your-username/your-frontend-repo.git
      
  2. Navigate to Your Backend Directory:

    • Go to the backend folder to install dependencies:

        cd your-backend-repo
        npm install
      

Step 5: Deploy the Backend (Node.js/Express)

  1. Set Up Environment Variables:

    • If your project uses environment variables (e.g., for MongoDB connection string, JWT secrets), create a .env file and add the necessary variables.
  2. Run Your Backend:

    • Use PM2 (a process manager for Node.js) to keep your server running in the background:

        sudo npm install -g pm2
        pm2 start server.js
        pm2 save
      

This will ensure that your backend server is always running.


Step 6: Deploy the Frontend (React)

  1. Navigate to the Frontend Directory:

    • Go to your frontend folder:

        cd your-frontend-repo
      
  2. Install Dependencies:

     npm install
    
  3. Build the React App:

    • Build your React app for production:

        npm run build
      
  4. Copy the Build to Nginx:

    • Copy the build files to the Nginx web directory:

        sudo cp -r build/* /var/www/html/
      

Step 7: Configure Nginx

  1. Edit Nginx Configuration:

    • Configure Nginx to serve your React app and reverse proxy your backend API:

        sudo nano /etc/nginx/sites-available/default
      

Example configuration:

    server {
        listen 80;

        server_name your-domain.com;

        location / {
            root /var/www/html;
            try_files $uri /index.html;
        }

        location /api/ {
            proxy_pass http://localhost:5000; # your backend server address
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection 'upgrade';
            proxy_set_header Host $host;
            proxy_cache_bypass $http_upgrade;
        }
    }
  1. Restart Nginx:

    • Apply the changes:

        sudo systemctl restart nginx
      

Step 8: Test Your Application

  1. Access Your Application:

    • Open a web browser and go to your EC2 instance’s public IP (e.g., http://your-ec2-public-ip) or your domain (if configured).

    • You should see your React frontend being served by Nginx, and it will be able to communicate with your backend.


Conclusion

Congratulations! You’ve successfully deployed a MERN stack application on an Amazon EC2 instance. You’ve learned how to set up the EC2 instance, install necessary software, deploy both the backend and frontend, configure Nginx as a reverse proxy, and ensure everything is running smoothly.

This guide should help you deploy any MERN stack application, and you can now start building more complex projects or scale your application using AWS features like Load Balancers and Auto Scaling.