πŸš€ Deploy Node.js on AWS EC2

ec2

Deploying a Node.js app from Windows β†’ WSL β†’ AWS EC2, step-by-step, clearly and cleanly.

Reference:Sam Meech-Ward’s Guide

πŸ’‘ Pro Tip: If you’ve used other AWS services (like Route 53, CloudFront, Lambda, RDS), list them in your resume or project to show off your experience!

Why Choose EC2 Over Apache?

TL;DR:

  • Learn Apache for basic web server setup and personal projects.
  • Learn EC2 for production-ready, scalable, DevOps-style deployments.

EC2 vs Apache

Apache:

  • βœ… Easy to get started
  • βœ… Great for static sites or small apps
  • ❌ Not scalable by itself
  • ❌ Lacks built-in tools (monitoring, backups, etc.)

EC2:

  • βœ… Cloud VM β€” run anything on it
  • βœ… Supports scaling, snapshots, monitoring, IAM, etc.
  • βœ… DevOps-ready
  • ❌ Steeper learning curve
  • ❌ You still need to configure Apache, Node.js, etc.

πŸ’‘ Simple Analogy: EC2 is the house. Apache is the kitchen. You install Apache inside EC2 to β€œcook” your web content.


πŸ“¦ Deployment Goal

Deploy your local Node.js app (port 5001) to AWS EC2 using WSL and rsync.

πŸ“˜ Step-by-Step Deployment Guide

  1. Test app locally:
    npm install npm start

    Visit: http://localhost:5001

  2. Set up WSL:
    wsl --install

    Then restart and install rsync:

    sudo apt update sudo apt install rsync
  3. Go to your Node.js folder in WSL:
    cd "/mnt/c/Users/Dell Inspiron/Documents/GitHub/node-express-ec2"
  4. Move your SSH key to WSL:
    cp "/mnt/c/Users/Dell Inspiron/.ssh/ssh1.pem" ~/.ssh/ chmod 400 ~/.ssh/ssh1.pem
  5. Run rsync to upload app to EC2:
    rsync -avz --exclude 'node_modules' --exclude '.git' --exclude '.env' \ -e "ssh -i ~/.ssh/ssh1.pem" \ . ubuntu@ec2-YOUR-PUBLIC-IP.compute-1.amazonaws.com:~/app
  6. SSH into EC2:
    ssh -i ~/.ssh/ssh1.pem ubuntu@ec2-YOUR-PUBLIC-IP.compute-1.amazonaws.com
  7. Set up Node.js environment:
    cd ~/app sudo apt update sudo apt install -y nodejs npm npm install npm start
  8. Access from browser:

    Update Inbound Rules in EC2 to allow port 5001, then visit:

    http://EC2_PUBLIC_IP:5001

βš™οΈ One-Click Deployment Script (Optional)

1. Create Script

nano deploy.sh

Paste this:

#!/bin/bash

    KEY_PATH="$HOME/.ssh/ssh1.pem"
    REMOTE_USER="ubuntu"
    REMOTE_HOST="ec2-YOUR-PUBLIC-IP.compute-1.amazonaws.com"
    REMOTE_DIR="~/app"

    echo "πŸš€ Starting deployment to $REMOTE_HOST"

    rsync -avz --exclude 'node_modules' --exclude '.git' --exclude '.env' \
    -e "ssh -i $KEY_PATH" \
    . $REMOTE_USER@$REMOTE_HOST:$REMOTE_DIR

    echo "βœ… Code synced. Logging into EC2..."
    ssh -i $KEY_PATH $REMOTE_USER@$REMOTE_HOST << 'EOF'
      cd ~/app
      npm install
      npm start
    EOF

2. Make Script Executable

chmod +x deploy.sh

3. Deploy

./deploy.sh