How to Install PM2 and Deploy Node.js on Ubuntu 24.04

Serdar Tekin
Serdar Tekin
Co-Founder & CTO
IntermediateUpdated 18 min read~60 minutes total
Node.jsPM2Ubuntu 24.04NginxExpressProcess Manager
Last reviewed:
Tutorial
How to Install PM2 and Deploy Node.js on Ubuntu 24.04
rafftechnologies.com/learn

Prerequisites

  • A Raff VM running Ubuntu 24.04, SSH access, a non-root user with sudo privileges, Node.js 24 LTS and npm installed, and a domain or server address for testing Nginx

Keep your Node.js app running with PM2 on your own Ubuntu 24.04 server.

Tested on 2 vCPU and 4 GB RAM: $17.99 a month

  1. 1Pick a Linux imageUbuntu, Debian and more, with your SSH key added.
  2. 2Choose a sizeFrom $4.99 a month. Resize when your app grows.
  3. 3Connect over SSHYour server is up in about 55 seconds.

Ubuntu, Debian and other Linux distributions with full root and SSH access, up and running in about 55 seconds.

PM2 is a production process manager for Node.js applications. On Ubuntu 24.04, you can install PM2 with npm, use it to keep Node.js processes running after SSH disconnects or crashes, restore applications after reboot with systemd, and run stateless applications across multiple workers with cluster mode.

For a complete deployment decision framework, read Application Deployment on a Linux VM.

On a Raff Linux VM, you can run a Node.js application as a long-lived service with PM2 while keeping the application port private behind Nginx. This tutorial uses Node.js 24 LTS, a small Express application, PM2 cluster mode on the tested 2 vCPU VM, systemd startup persistence, graceful reload handling, and an Nginx reverse proxy. You will also verify that port 3000 listens only on 127.0.0.1, so the Node.js process is not exposed directly to the internet.

PM2 cluster mode can run multiple instances of a networked Node.js application on the same port, but PM2's current documentation explicitly recommends keeping clustered applications stateless. In-memory sessions, local worker state, and similar data should be moved to a shared service before scaling workers. PM2 also documents reload as a rolling reload path for clustered HTTP applications, with a fallback to a normal restart if the reload cannot complete. For that reason, this tutorial adds graceful shutdown handling instead of promising zero downtime under every failure condition.

Node.js 24 remains an LTS release as of November 23, 2026. Node.js 24.22.3, released October 21, includes security fixes, so use a current patched Node.js 24 LTS build for production. If Node.js is not installed yet, follow Node.js on Ubuntu 24.04 before continuing. This patch-level note is a documentation update; no new VM test is claimed.

Step 1 — Verify Node.js 24 LTS and the Server User

Run the application as a normal user with sudo privileges rather than as root.

Check your user and Node.js installation:

Bash
whoami node --version npm --version command -v node

The Node.js project lists Node.js 24 as LTS. As of November 23, 2026, 24.22.3 is a security release in this line. Checking only that the major version starts with v24 does not prove the machine has the latest security fixes; also verify the installed patch level against the official LTS release notes.

If node --version does not report a supported v24.x.x LTS build, complete the Node.js installation procedure linked in the introduction before continuing.

Verify: whoami should show your non-root deployment user, node --version should report v24.x.x, and npm --version should run without an error.

Step 2 — Create a Production Application Directory

Create a directory under /srv and give your deployment user ownership:

Bash
sudo mkdir -p /srv/myapp sudo chown "$USER:$USER" /srv/myapp cd /srv/myapp

Initialize npm and install Express:

Bash
npm init -y npm install express

Confirm the project files exist:

Bash
ls -la npm ls express

For your own application, deploy the repository into /srv/myapp instead of creating this sample project. Keep secrets such as API keys and database passwords out of version-controlled files.

Verify: /srv/myapp/package.json should exist and npm ls express should show Express installed without dependency errors.

Step 3 — Create a Localhost-Only Express App with Graceful Shutdown

Create app.js:

Bash
cat > /srv/myapp/app.js <<'EOF' const express = require('express'); const app = express(); const host = '127.0.0.1'; const port = Number(process.env.PORT || 3000); app.get('/', (req, res) => { res.json({ message: 'Node.js is running under PM2', pid: process.pid, }); }); app.get('/health', (req, res) => { res.status(200).json({ status: 'ok', pid: process.pid }); }); const server = app.listen(port, host, () => { console.log(`Listening on http://${host}:${port}`); if (process.send) process.send('ready'); }); function shutdown(signal) { console.log(`${signal} received; closing HTTP server`); const forceExit = setTimeout(() => { console.error('Graceful shutdown timed out'); process.exit(1); }, 8000); forceExit.unref(); server.close((error) => { clearTimeout(forceExit); if (error) { console.error(error); process.exit(1); } process.exit(0); }); } process.on('SIGINT', () => shutdown('SIGINT')); process.on('SIGTERM', () => shutdown('SIGTERM')); EOF

PM2's graceful-shutdown guidance recommends handling the stop signal, stopping new connections, finishing active work, closing external resources, and then exiting. In a real application, add database, queue, or cache cleanup before process.exit(0).

Verify:

Bash
node --check /srv/myapp/app.js

The command should exit with no syntax error.

Step 4 — Test the Node.js App Before Adding PM2

Start the application in the foreground:

Bash
cd /srv/myapp NODE_ENV=production PORT=3000 node app.js

In a second SSH session, test both routes:

Bash
curl -fsS http://127.0.0.1:3000/ curl -fsS http://127.0.0.1:3000/health

Check the listening address:

Bash
ss -lntp | grep ':3000'

The listener should be on 127.0.0.1:3000, not 0.0.0.0:3000 or [::]:3000.

Return to the first session and press Ctrl+C. The app should log that it received SIGINT and exit.

Verify: Both local requests should succeed, the health route should return "status":"ok", and port 3000 should be loopback-only.

Step 5 — Install PM2 on Ubuntu 24.04

If Node.js was installed system-wide with the NodeSource method from the Raff Node.js tutorial, install PM2 globally with:

Bash
sudo npm install -g pm2

If your Node.js runtime is managed by nvm under your user account, run the same npm command without sudo:

Bash
npm install -g pm2

Do not mix a system-wide Node.js runtime and an nvm-managed PM2 installation unless you deliberately manage both paths.

Verify PM2:

Bash
pm2 --version command -v pm2

If an existing application already has a start script in package.json, PM2 can run that npm script directly:

Bash
pm2 start npm --name myapp -- start

For this tutorial we continue with an ecosystem file because it keeps the worker count, readiness, restart, and environment settings together.

Verify: pm2 --version should return a version number and command -v pm2 should resolve to the installation associated with your intended Node.js runtime.

Step 6 — Create a PM2 Ecosystem File for the Tested 2 vCPU Setup

Create the PM2 configuration:

Bash
cat > /srv/myapp/ecosystem.config.js <<'EOF' module.exports = { apps: [ { name: 'myapp', script: './app.js', cwd: '/srv/myapp', instances: 2, exec_mode: 'cluster', wait_ready: true, listen_timeout: 10000, kill_timeout: 10000, restart_delay: 1000, watch: false, merge_logs: true, env: { NODE_ENV: 'production', PORT: 3000, }, }, ], }; EOF

The tested Raff VM has 2 vCPU, so this example uses two workers explicitly instead of instances: 'max'. On a 1 vCPU VM, set instances: 1. On larger machines, increase workers only after measuring your application and confirming that it is stateless.

Do not put secrets in this ecosystem file if it is committed to source control. Use your deployment's secret-management method or a restrictive runtime configuration file that is excluded from Git.

PM2's ecosystem-file reference documents instances, exec_mode, wait_ready, listen_timeout, kill_timeout, and restart controls. The combination here lets PM2 wait for the app's explicit ready message and gives the app time to finish requests during a reload.

Verify:

Bash
node --check /srv/myapp/ecosystem.config.js

The configuration should pass Node.js syntax validation.

Step 7 — Run Node.js with PM2 Cluster Mode

Start the ecosystem configuration:

Bash
cd /srv/myapp pm2 start ecosystem.config.js

Check status:

Bash
pm2 status pm2 describe myapp

Make several local requests:

Bash
for i in 1 2 3 4 5 6; do curl -fsS http://127.0.0.1:3000/health echo done

On the tested 2-worker setup, the responses should normally show more than one process ID over repeated requests. Do not depend on a strict alternating order.

If your application stores sessions or other state in process memory, do not enable multiple workers until that state has been moved to a shared store.

Verify: pm2 status should show two myapp instances online on the tested 2 vCPU setup, and repeated health requests should succeed.

Step 8 — Configure PM2 to Restore the App After Reboot

Generate the startup hook as your normal deployment user:

Bash
pm2 startup systemd

PM2 prints a sudo command containing the correct user, home directory, PM2 path, and Node.js path. Copy and run the exact command PM2 prints rather than copying a path from another server.

Save the current process list:

Bash
pm2 save

PM2's startup documentation uses the saved process list to resurrect applications after boot.

Check the generated service:

Bash
sudo systemctl is-enabled "pm2-$USER" sudo systemctl status "pm2-$USER" --no-pager

If you later change an nvm-managed Node.js version, PM2 recommends regenerating the startup hook because the Node.js path embedded in the service can change.

Verify: The pm2-$USER service should be enabled, and pm2 save should complete successfully.

Step 9 — Put Nginx in Front of the Private Node.js Port

Install Nginx if it is not already present:

Bash
sudo apt update sudo apt install -y nginx

Create a server block. Replace your-domain.com with your domain or the server address you use for testing:

Bash
sudo tee /etc/nginx/sites-available/myapp > /dev/null <<'EOF' server { listen 80; server_name your-domain.com; location / { proxy_pass http://127.0.0.1:3000; proxy_http_version 1.1; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_read_timeout 60s; } } EOF

PM2 and Nginx solve different problems. PM2 keeps the Node.js process running and manages its workers; Nginx owns the public HTTP/HTTPS edge and proxies requests to the private application port. Using both keeps process management separate from public web traffic.

Enable the site and validate Nginx before reloading:

Bash
sudo ln -sfn /etc/nginx/sites-available/myapp /etc/nginx/sites-enabled/myapp sudo nginx -t sudo systemctl reload nginx

For HTTPS, continue with Secure Nginx with Let's Encrypt on Ubuntu 24.04 after the HTTP proxy works.

Verify:

Bash
curl -fsS http://your-domain.com/health

The response should contain "status":"ok".

Step 10 — Confirm the Node.js Port Is Not Publicly Exposed

Check the local listener again:

Bash
ss -lntp | grep ':3000'

Expected listening address:

Text
127.0.0.1:3000

Do not add a firewall rule that exposes TCP 3000 to the internet when Nginx is the intended public entry point. Only Nginx needs to accept public HTTP/HTTPS traffic for this architecture.

You can also test locally that Nginx and the app are separate layers:

Bash
curl -fsS http://127.0.0.1:3000/health curl -fsS http://your-domain.com/health

Verify: Both requests should succeed, while ss should still show the application itself bound only to 127.0.0.1:3000.

Step 11 — Test a Rolling Reload and Graceful Shutdown

PM2 cluster mode supports rolling reloads for HTTP applications:

Bash
pm2 reload myapp

Watch the application state:

Bash
pm2 status pm2 logs myapp --lines 30

The app's signal handler should allow active HTTP connections to finish before the worker exits. PM2's current cluster documentation states that reload keeps workers available one by one, but also notes that a failed reload can fall back to a normal restart. Treat reloads as a safer deployment mechanism, not as an unconditional availability guarantee.

For applications with database or queue connections, close those resources inside the shutdown handler before exiting.

Verify: The app should remain online after pm2 reload myapp, and a new request should succeed:

Bash
curl -fsS http://127.0.0.1:3000/health

Step 12 — Check Logs, Restarts, and Runtime State

Inspect the PM2 process details:

Bash
pm2 status pm2 describe myapp

View recent logs without leaving a long-running terminal session:

Bash
pm2 logs myapp --lines 50 --nostream

For interactive CPU and memory observation:

Bash
pm2 monit

Exit the monitor when finished. Use the measurements from your own workload to decide worker count, memory thresholds, and VM sizing; this tutorial does not assume a universal requests-per-second or latency figure for Node.js applications.

Verify: Both workers should remain online on the tested setup, restart counts should be understandable from your deployment actions, and recent logs should not show crash loops or binding errors.

Step 13 — Run the Final End-to-End Verification

Run the complete verification set:

Bash
node --version pm2 --version pm2 status sudo systemctl is-enabled "pm2-$USER" sudo nginx -t ss -lntp | grep ':3000' curl -fsS http://127.0.0.1:3000/health curl -fsS http://your-domain.com/health

The deployment is complete when Node.js 24 LTS is active, PM2 shows the intended worker count online, the PM2 systemd startup unit is enabled, Nginx configuration is valid, the application listens only on loopback, and both the direct local health check and Nginx-proxied health check succeed.

If you want to verify reboot recovery, schedule an appropriate maintenance window and reboot the VM. After reconnecting, run pm2 status and the health checks again rather than rebooting a production server casually during deployment.

Verify: Every command above must complete successfully, and the Node.js listener must remain 127.0.0.1:3000.

Deploy your Node.js app on Raff.

Tested on 2 vCPU and 4 GB RAM: $17.99 a month · 14-day money-back guarantee

Deploy Your Server

Cleanup (optional)

If this was only a test deployment, remove the application from PM2 first:

Bash
pm2 delete myapp

If other PM2 applications still run on the VM, save the remaining process list:

Bash
pm2 save

If myapp was the last PM2 application and you intentionally want an empty resurrect list, PM2's startup documentation provides:

Bash
pm2 cleardump

Remove the Nginx site and reload Nginx:

Bash
sudo rm -f /etc/nginx/sites-enabled/myapp sudo rm -f /etc/nginx/sites-available/myapp sudo nginx -t sudo systemctl reload nginx

Remove the sample application only after confirming the path contains no production data:

Bash
rm -rf /srv/myapp

Do not run pm2 unstartup or uninstall PM2 if the server hosts other PM2-managed applications.

Verify: pm2 status should no longer list myapp, nginx -t should still succeed, and the removed site should no longer proxy to the sample application.

Troubleshooting

PM2 reports errored or repeated restarts

Run pm2 logs myapp --lines 80 --nostream and pm2 describe myapp. Confirm the process uses the intended Node.js 24 runtime, environment variables, and loopback port. Correct the application error before restarting it.

Nginx returns 502 Bad Gateway

Run curl -fsS http://127.0.0.1:3000/health, sudo nginx -t, and sudo tail -n 50 /var/log/nginx/error.log. Resolve PM2 worker failures, socket/port mismatches, or proxy configuration errors before reloading Nginx.

App does not return after reboot

Check systemctl is-enabled "pm2-$USER", pm2 status, and journalctl -u "pm2-$USER" -n 50 --no-pager. If your Node.js NVM path changed, regenerate PM2 startup with the command printed by PM2 and save the intended process list.

Conclusion

You installed PM2 on Ubuntu 24.04 and deployed a Node.js 24 application with explicit cluster sizing for the tested 2 vCPU VM, graceful shutdown handling, systemd startup persistence, and Nginx as the public reverse proxy. The application port stays on 127.0.0.1, PM2 manages worker lifecycle, and the final checks verify both local application health and the Nginx path.

The main production decisions should come from your own workload rather than generic performance numbers. Scale PM2 workers only when the app is stateless, measure CPU and memory before changing worker counts, keep secrets out of committed ecosystem files, and regenerate the PM2 startup hook when an nvm-managed Node.js path changes. For HTTPS, complete the Nginx certificate procedure already linked in Step 9. For the underlying runtime, see Install Node.js on Ubuntu. For the broader build, release, and rollback architecture, read Application Deployment on a Linux VM.

Was this article helpful?
Serdar Tekin
Serdar Tekin
Co-Founder & CTO

Co-Founder & CTO at Raff, focused on cloud infrastructure, systems architecture, security, reliability, and production operations.

Keep your Node.js app running with PM2 on your own Ubuntu 24.04 server.

Tested on 2 vCPU and 4 GB RAM: $17.99 a month

Ubuntu, Debian and other Linux distributions with full root and SSH access, up and running in about 55 seconds.

14-day money-back guarantee

Frequently asked questions

How do I install PM2 on Ubuntu 24.04?
Install a supported Node.js LTS release first. With a system-wide Node.js installation, run `sudo npm install -g pm2`; with nvm, install PM2 as the same normal user without `sudo`. Verify with `pm2 --version`.
What is the difference between PM2 and Nginx?
PM2 supervises Node.js processes, manages restarts and worker reloads, and restores saved apps after reboot. Nginx handles public HTTP/HTTPS and proxies traffic to the private Node.js application port. They serve separate roles and are often deployed together.
Should I use PM2 cluster mode for every Node.js app?
No. Cluster mode is appropriate for networked Node.js applications that are stateless across workers. In-memory sessions, local worker state, and similar data should be moved to shared services before running multiple instances.
Does `pm2 reload` guarantee zero downtime?
PM2 reloads clustered HTTP workers one at a time and is designed to keep workers available during reload. PM2 also documents that a failed reload can fall back to a normal restart, so graceful shutdown and health verification are still important.
Should port 3000 be open to the internet?
Not in the Nginx reverse-proxy architecture used here. Bind the Node.js app to `127.0.0.1:3000` and let Nginx receive public HTTP or HTTPS traffic.

Related Articles

View all →