Table of Contents
Node.js is widely used for building fast, scalable backend services. PM2 keeps your Node.js app alive, restarts it on crashes, and manages it as a system service. This guide installs Node.js properly and runs a production-ready Node server with PM2 — no fluff, no unrelated steps.
Step 1: Update System Packages
Start with a clean system.
sudo apt update && sudo apt upgrade -y
Step 2: Install Node.js (Recommended via NodeSource)
Ubuntu repositories are often outdated. Use NodeSource for a modern LTS version.
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
sudo apt install -y nodejs
Verify installation:
node -v
npm -v
Step 3: Create a Simple Node.js Server
Create a project directory:
mkdir node-app && cd node-app
Initialize the project:
npm init -y
Create server.js:
nano server.js
Paste:
const http = require("http");
const server = http.createServer((req, res) => {
res.writeHead(200, { "Content-Type": "text/plain" });
res.end("Node.js server is running\n");
});
server.listen(3000, () => {
console.log("Server running on port 3000");
});
Test it:
node server.js
Visit:
http://server-ip:3000
Stop it with Ctrl + C.
Step 4: Install PM2 Globally
PM2 manages your Node process in production.
sudo npm install -g pm2
Verify:
pm2 -v
Step 5: Run Node App with PM2
Start the app:
pm2 start server.js --name node-server
Check status:
pm2 list
View logs:
pm2 logs node-server
Step 6: Enable PM2 Startup on Boot
Generate startup script:
pm2 startup
PM2 will print a command. Copy and run it exactly (usually starts with sudo env ...).
Save current process list:
pm2 save
Now your Node server will auto-start after reboot.
Step 7: Open Firewall Port (If UFW Is Enabled)
Allow your app port:
sudo ufw allow 3000/tcp
sudo ufw reload
Step 8: Update and Restart the App
When code changes:
pm2 restart node-server
Or reload with zero downtime:
pm2 reload node-server
If you’re running Node.js without PM2 in production, your service will go down eventually. PM2 is not optional — it’s the minimum standard.
