Deploy MERN Stack App on AWS EC2
1. Set Up Your EC2 Instance
- Go to AWS and create an EC2 instance (a virtual server).
- Choose an Amazon Linux 2 template.
- Select a small server size (like t2.micro).
- Configure the instance to allow HTTP, HTTPS, and SSH traffic.
- Download the key file provided by AWS.
2. Connect to Your EC2 Instance
- Open your terminal (or use PuTTY on Windows).
- Connect to your EC2 instance using the command:
ssh -i /path/to/your-key-file.pem ec2-user@your-ec2-public-dns
3. Install Required Software
- Update the server:
sudo yum update -y
- Install Node.js (for running JavaScript):
curl -sL https://rpm.nodesource.com/setup_14.x | sudo -E bash - sudo yum install -y nodejs
- Install MongoDB (your database):
echo "[mongodb-org-4.2] name=MongoDB Repository baseurl=https://repo.mongodb.org/yum/amazon/2/mongodb-org/4.2/x86_64/ gpgcheck=1 enabled=1 gpgkey=https://www.mongodb.org/static/pgp/server-4.2.asc" | sudo tee /etc/yum.repos.d/mongodb-org-4.2.repo sudo yum install -y mongodb-org sudo systemctl start mongod sudo systemctl enable mongod
4. Deploy Your Application
- Copy your app from GitHub:
git clone https://github.com/your-repo/your-mern-app.git cd your-mern-app
- Install app dependencies:
npm install cd client npm install cd ..
- Build the frontend:
cd client npm run build cd ..
- Start your app:
npm start
5. Make Your App Accessible Online
- Install Nginx (a web server):
sudo amazon-linux-extras install nginx1 -y
- Configure Nginx to pass traffic to your app:
Add the following lines inside thesudo vim /etc/nginx/nginx.conf
server
block:server { listen 80; server_name your-ec2-public-dns; location / { 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; proxy_set_header X-Forwarded-Proto $scheme; } }
- Restart Nginx:
sudo systemctl restart nginx
6. Access Your Application
Open your web browser and go to your EC2 instance's public DNS (the address provided by AWS). Your MERN app should now be live!
```
0 Comments