MERN Stack Deployment Guide: Setting Up Backend on AWS EC2
Why Deploy MERN Stack Backend on AWS EC2
AWS EC2 offers a secure, scalable, and cost-effective environment for hosting Node.js and Express.js servers with MongoDB integration. With EC2, you can:
- Scale server resources based on demand.
- Ensure high availability with AWS’s global infrastructure.
- Secure your backend with AWS security groups and VPC configurations.
- Integrate seamlessly with other AWS services like RDS, S3, or Elastic Load Balancer.
Prerequisites
Before starting, ensure you have:
- An AWS account.
- Basic knowledge of MERN stack development (MongoDB, Express.js, Node.js).
- A MERN stack application ready for deployment.
- Familiarity with SSH, Git, and Linux commands.
- A domain name (optional for custom URLs).
Step-by-Step Guide to Deploying MERN
Step 1: Launch an AWS EC2 Instance
- Sign in to AWS Management Console: Navigate to the EC2 dashboard.
- Choose an AMI: Select an Amazon Linux 2 or Ubuntu Server AMI for compatibility with Node.js.
- Select Instance Type: For small-scale MERN apps, a t2.micro instance (free tier eligible) is sufficient. For larger apps, choose a higher-tier instance like t3.medium.
- Configure Instance Details: Set up a VPC and subnet for network isolation.
- Enable auto-assign public IP for external access.
- Add Storage: Allocate sufficient storage (e.g., 10-20 GB) for your app and database.
- Configure Security Group:Allow inbound traffic on ports
- 22: (SSH for remote access).
- 80 (HTTP for web traffic).
- 443 (HTTPS for secure traffic).
- 3000 or custom port for your Node.js app.
- Launch Instance: Download the .pem key pair for SSH access.
Step 2: Connect to Your EC2 Instance
- Use an SSH client (e.g., Terminal on macOS/Linux or PuTTY on Windows).
- Connect using the command:
ssh -i your-key.pem ec2-user@console.log( 'Code is Poetry' );
- Replace your-key.pem with your key file and <your-ec2-public-ip> with the instance’s public IP.
- Update the instance:
sudo apt update && sudo apt upgrade -y # For Ubuntu
sudo yum update - # For Amazon Linux
Step 3: Set Up the Backend Environment
- Install Node.js and npm:For Ubuntu:
curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash - sudo apt install -y nodejs
- For Amazon Linux:
curl -sL https://rpm.nodesource.com/setup_18.x | sudo bash - sudo yum install -y nodejs
- Verify installation:
node -v # for verify node version in server
npm -v # for npm version in server
Install MongoDB (if hosting the database on the same EC2 instance):
- Follow MongoDB’s official installation guide for your OS.
- Alternatively, use MongoDB Atlas for a cloud-hosted database to reduce EC2 load.
- Install Git:
sudo apt install git -y # Ubuntu oprating System lts
sudo yum install git -y # Amazon Linux
Step 4: Deploy Your MERN Backend Code
Clone Your Repository
- Navigate to your desired directory (e.g., `/home/ubuntu`).
- Clone your backend code
git clone
Install Dependencies
- Navigate to your backend folder
cd
npm install
Configure Environment Variables
- Create a .env file in the backend folder
touch .env
- Add necessary variables, e.g.
PORT=3000
MONGODB_URI=
JWT_SECRET=
Test the Backend
- Start the server
node server.js # or npm start
- Access http://<your-ec2-public-ip>:<port> to verify the backend is running.
Step 5: Set Up a Process Manager (PM2)
To ensure your Node.js app runs continuously and restarts on failure:
- Install PM2 globally:
npm install -g pm2
- Start your app with PM2:
pm2 start server.js --name "mern-backend"
- Save PM2 configuration:
pm2 save
pm2 startup
- Follow the generated command to enable PM2 on system boot.
Step 6: Configure Nginx as a Reverse Proxy
- Install Nginx
sudo apt install nginx -y # Ubuntu
sudo yum install nginx -y # Amazon Linux
- Configure Nginx
sudo nano /etc/nginx/sites-available/default # Ubuntu
sudo nano /etc/nginx/conf.d/mern.conf # Amazon Linux
- Add the following configuration:
server {
listen 80;
server_name ;
location / {
proxy_pass http://localhost:3000;
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;
}
}
- Restart Nginx
sudo systemctl restart nginx
sudo systemctl enable nginx
Step 7: Secure Your Backend with SSL (Optional)
For production, secure your app with HTTPS
- Install Certbot for Let’s Encrypt:
sudo apt install certbot python3-certbot-nginx -y # Ubuntu
sudo yum install certbot python3-certbot-nginx -y # Amazon Linux
- Obtain an SSL certificate:
sudo certbot --nginx -d
- Follow prompts to configure HTTPS. Certbot auto-updates Nginx for SSL.
Step 8: Monitor and Scale
- Monitor Performance**: Use AWS CloudWatch to track EC2 metrics like CPU and memory usage.
- Scale: Set up an Auto Scaling Group to handle traffic spikes.
- Backup: Regularly back up your MongoDB database and EC2 instance snapshots.
Best Practices for MERN Stack Deployment on AWS EC2
- Use Environment Variables: Store sensitive data like API keys and database URIs securely.
- Enable Security Groups: Restrict access to only necessary ports (22, 80, 443).
- Regular Updates: Keep Node.js, MongoDB, and OS packages updated.
- CI/CD Pipeline: Integrate tools like GitHub Actions for automated deployments.
- Load Balancing: Use AWS Elastic Load Balancer for high-traffic apps.
Finally
Deploying a MERN stack backend on AWS EC2 is a straightforward process when following this guide. By setting up Node.js, MongoDB, PM2, and Nginx, you can create a scalable, secure, and high-performance backend for your MERN application. For advanced setups, consider integrating AWS services like RDS for MongoDB or Route 53 for domain management.
“Happy Coding”
Subscribe to Our Newsletter
Get the latest updates and articles directly in your inbox.