π₯οΈ Node.js Hello World on EC2 β Keep It Running Forever with PM2
Great for testing simple deployments on any cloud (AWS EC2, DigitalOcean, etc.).
β Full Setup Guide (Step-by-Step)
π§± Step 1: Install Node.js and NPM Using NVM
# Become root
sudo su -
# Install NVM (Node Version Manager)
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.34.0/install.sh | bash
# Activate NVM
. ~/.nvm/nvm.sh
# Install latest Node.js
nvm install node
# Verify installation
node -v
npm -v
π§ Step 2: Install Git and Clone the Repository
# Update packages
sudo apt-get update -y
# Install Git
sudo apt-get install git -y
# Verify Git version
git --version
# Clone the Node.js sample repo
git clone https://github.com/yeshwanthlm/nodejs-on-ec2.git
# Move into the project directory
cd nodejs-on-ec2
# Install dependencies
npm install
π Step 3: Start the Application (For Testing)
npm start
Your app will now serve "A Monk in Cloud"
β but it will stop when the terminal is closed or the server reboots. To fix that, letβs keep it running with PM2 π
π Step 4: Install and Use PM2 to Keep App Alive
π₯ Install PM2 globally:
npm install -g pm2
βΆοΈ Start the App with PM2:
pm2 start index.js --name BackendAPI
π Replace
index.js
with the name of your main JS file if different.
β»οΈ Step 5: Keep App Running After Reboot
pm2 startup
Copy and run the command it outputs (something like this):
sudo env PATH=$PATH:/root/.nvm/versions/node/vXX/bin /root/.nvm/versions/node/vXX/lib/node_modules/pm2/bin/pm2 startup systemd -u root --hp /root
Then save the PM2 process list:
pm2 save
π Step 6: PM2 Useful Commands
pm2 list # Show running apps
pm2 logs # Show app logs
pm2 restart monk-app # Restart the app
pm2 stop monk-app # Stop the app
pm2 delete monk-app # Remove it from PM2
β Final Result
- Node.js is installed with NVM
- App is deployed and running
- PM2 keeps it alive forever
- App auto-starts after reboot
β¨ Optional
You can also:
- Use NGINX as a reverse proxy for clean domain access
- Add HTTPS with Letβs Encrypt
- Connect a CI/CD pipeline
Let me know in the comments if you'd like a guide for any of those! π
Top comments (0)