- AWS account
- Node.js and NPM installed locally
- Basic knowledge of Linux and SSH
- Project ready to deploy
- Log in to your AWS Management Console.
- Navigate to the EC2 service.
- Click on "Launch Instance."
- Select an Amazon Machine Image (AMI): Choose Ubuntu 20.04.
- Select Instance Type: Choose "t2.micro" (Free tier eligible).
- Configure Instance:
- Add a key pair for SSH access.
- Add a security group with rules to allow HTTP, HTTPS, and SSH traffic.
- Launch the instance.
- Log in to your domain registrar (e.g., GoDaddy, Namecheap, etc.).
- Go to the DNS management section for your domain.
- Add the following records:
- A Record:
- Host:
@ - Points to:
your-ec2-public-ip - TTL: Default or 1 hour
- Host:
- CNAME Record (optional, for
www):- Host:
www - Points to:
your-domain.com - TTL: Default or 1 hour
- Host:
- A Record:
- Save the changes.
- It may take a few minutes to a few hours for DNS propagation.
- Download the private key file (.pem) for the key pair you created.
- Open your terminal and navigate to the directory containing the .pem file.
- Run the command:
ssh -i "your-key.pem" ubuntu@your-ec2-public-ip - Replace "your-key.pem" with your key file and "your-ec2-public-ip" with the public IP of your instance.
- Update the system:
sudo apt update && sudo apt upgrade -y - Install Node.js and NPM:
curl -fsSL https://deb.nodesource.com/setup_16.x | sudo -E bash -
sudo apt install -y nodejs
3. Verify installation:bash
node -v
npm -v
4. Install PM2 globally for process management:bash
sudo npm install pm2 -g
```
- Clone your project repository:
git clone https://github.com/your-username/your-repo.git
- Navigate to the project directory:
cd your-repo - Install dependencies:
npm install
- Start the application with PM2:
Replace
pm2 start app.js
app.jswith your main entry file. - Save the PM2 process list to auto-start on reboot:
pm2 save pm2 startup
- Install Nginx:
sudo apt install nginx
- Configure Nginx:
Replace the file content with:
sudo nano /etc/nginx/sites-available/default
Replaceserver { listen 80; server_name your-ec2-public-ip; 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; } }your-ec2-public-ipwith your instance's public IP and3000with your app's port. - Restart Nginx:
sudo systemctl restart nginx
- Open your browser and visit your domain (e.g.,
http://your-domain.com). - Your application should be live.
For a full detailed guide to hosting a Node.js app on AWS EC2, see this link: https://waterrmalann.notion.site/A-simple-guide-to-hosting-a-Node-js-app-on-AWS-EC2-6e05ee8c5689452f94a2c550f66aeecd
- Make sure to replace placeholders like
your-key.pem,your-ec2-public-ip, and3000with actual values. - Always keep your
.pemfile secure. - Use environment variables for sensitive data in your project.