Deploy Express.js Backend on AWS EC2

Steps to deploy ExpressJs app on AWS using EC2

Add .pem file to read mode, add SSH

chmod 400 your-key.pem
ssh -i "your-key.pem" ubuntu@ec2-YOUR-IP.compute.amazonaws.com

Steps to install latest Ubuntu packages & Node.js

sudo apt update
sudo apt upgrade -y
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
sudo apt install -y nodejs

Check if Node & NPM installed correctly

node -v
npm -v

Install Git to clone project from GitHub

sudo apt install git -y

Option A: Clone from GitHub

git clone https://github.com/your/repo.git
cd repo

Option B: Upload ZIP using SCP

scp -i your-key.pem file.zip ubuntu@YOUR-IP:/home/ubuntu

Install dependencies & create production build

npm install
npm run build

Check if the web service is running

npm start
http://YOUR_PUBLIC_IP:3000

Add ENV variables

nano .env
paste your env variables and save

Run the server permanently using PM2

sudo npm install pm2 -g
pm2 start index.js
pm2 save
pm2 startup

NGINX (Reverse Proxy) — Access app without port

Install & configure Nginx

sudo apt install nginx -y
sudo nano /etc/nginx/sites-available/default
sudo truncate -s 0 /etc/nginx/sites-available/default

Paste this config

sudo systemctl restart nginx