DEV Community

arif chaudhary
arif chaudhary

Posted on

Deploy a Node.js App on EC2 and Keep It Running Forever with PM2

πŸŒ₯️ 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
Enter fullscreen mode Exit fullscreen mode

πŸ”§ 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
Enter fullscreen mode Exit fullscreen mode

πŸš€ Step 3: Start the Application (For Testing)

npm start
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

▢️ Start the App with PM2:

pm2 start index.js --name BackendAPI
Enter fullscreen mode Exit fullscreen mode

πŸ“ Replace index.js with the name of your main JS file if different.


♻️ Step 5: Keep App Running After Reboot

pm2 startup
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Then save the PM2 process list:

pm2 save
Enter fullscreen mode Exit fullscreen mode

πŸ“‹ 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
Enter fullscreen mode Exit fullscreen mode

βœ… 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)