Deploying a Simple MERN App on AWS EC2
Introduction
Deploying a MERN (MongoDB, Express, React, Node.js) application on AWS EC2 is a great way to understand cloud deployment. This guide walks you through the step-by-step process of deploying a basic MERN app on AWS EC2.
Prerequisites
Basic understanding of MERN stack
AWS account
GitHub account
MongoDB Atlas account
SSH client (such as Terminal or PuTTY)
Steps to Deploy MERN App on AWS EC2
1. Create a Simple MERN App
Develop a React frontend with basic features (e.g., add and view products).
Set up a Node.js and Express backend to handle API requests.
Use MongoDB Atlas as the database.
Ensure the app works locally before deployment.
2. Push Code to GitHub
Initialize a Git repository in your project folder.
Commit and push your code to a GitHub repository.
3. Set Up AWS EC2 Instance
Log in to your AWS account.
Launch a new EC2 instance (Ubuntu 22.04 recommended).
Choose an appropriate instance type (e.g., t2.micro for free tier users).
Configure security groups to allow inbound HTTP, HTTPS, and SSH connections.
Download the
.pem
key file to securely access the instance.
4. Connect to the EC2 Instance
Open the terminal and connect using SSH:
ssh -i your-key.pem ubuntu@your-ec2-ip-address
Update system packages:
sudo apt update && sudo apt upgrade -y
5. Install Node.js and Git
Install Node.js and npm:
curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash - sudo apt install -y nodejs
Verify installation:
node -v npm -v
Install Git:
sudo apt install git -y
6. Clone GitHub Repository
Clone your project repository:
git clone https://github.com/your-username/your-repo.git
Navigate to the project folder:
cd your-repo
7. Install Dependencies and Configure Environment
Install backend dependencies:
cd backend npm install
Install frontend dependencies:
cd frontend npm install
Update the backend
.env
file with MongoDB Atlas connection string and other environment variables.
8. Run the Application
Start the backend:
cd backend node server.js
Start the frontend:
cd frontend npm start
9. Access the Application
Open a browser and enter
http://your-ec2-ip-address:3000
to access the frontend.Use API endpoints (
http://your-ec2-ip-address:5000/api/products
) to verify backend functionality.
10. Keep the App Running in the Background
Use PM2
to keep the app running even after the terminal session is closed.
npm install -g pm2
pm2 start backend/server.js
pm2 start npm --name "frontend" -- start --prefix frontend
pm2 save
Conclusion
Congratulations! ๐ You have successfully deployed a simple MERN application on AWS EC2. This process helps you understand cloud deployment and prepares you for larger-scale applications.