Configure PM2 Startup Scripts and Log Rotation on a VPS

by Fahim Mahmud Chisti

Running Node.js with node server.js is fine locally, but in production the process dies when your SSH session closes or an unhandled error slips through, and it stays down until someone notices. This guide shows how to configure PM2 on a VPS: an ecosystem file, cluster mode with zero-downtime reloads, a systemd startup script so apps survive reboots, and log rotation so the disk never fills up.

Quick answer: Install PM2 with sudo npm install -g pm2, start your app from an ecosystem.config.js file, run pm2 startup and then the command it prints, run pm2 save, and add pm2-logrotate to cap log size.

  1. Install PM2 globally and check it with pm2 --version.
  2. Describe the app in ecosystem.config.js and start it with --env production.
  3. Run pm2 startup systemd as the app user and execute the sudo env PATH=… line it prints.
  4. Run pm2 save so the process list comes back after a reboot.
  5. Install pm2-logrotate and set a size limit and retention count.
In this guide
  1. Before You Start
  2. Step 1: Install PM2 and Start a Process
  3. Step 2: Write an Ecosystem File (ecosystem.config.js)
  4. Step 3: Use Cluster Mode for Zero-Downtime Reloads
  5. Step 4: Set Up a systemd Startup Script for Reboots
  6. Step 5: Rotate Logs Automatically with pm2-logrotate
  7. Step 6: Set Memory Limits and Auto-Restarts
  8. Step 7: Monitor Processes and Read Live Logs
  9. Common Problems and Fixes
  10. Frequently Asked Questions
  11. Next Steps for Your VPS Stack
Linux terminal showing PM2 process status and cluster management on a VPS

Before You Start

  • A Linux VPS (Ubuntu or Debian) with Node.js and npm installed, and SSH access as the non-root user that runs your app.
  • That user needs sudo rights for the global install and the startup script.
  • Your app’s entry file, such as server.js or dist/index.js, already on the server.
  • About 20 minutes. The reboot test at the end restarts the whole server, so run it at a quiet time.

Step 1: Install PM2 and Start a Process

PM2 runs as a background daemon (a program that keeps running after you log out) and supervises your Node.js processes. Run this on your VPS as a user with sudo privileges:

sudo npm install -g pm2

Verify the binary is in your PATH and check the installed version:

pm2 --version

It should print a version number. If you followed the guide to deploy Node.js on a Hostinger VPS with Nginx, you already have an entry point like server.js or dist/index.js. From your app’s folder, start it as a named process for a quick test:

pm2 start server.js --name "api-service"

pm2 list should show api-service with the status online. Ad-hoc CLI flags work for quick smoke tests, but for real deployments with environment variables and multiple workers, you want a configuration file in source control. Run pm2 delete api-service before moving on, so the test process does not compete with the real one for the same port.

Step 2: Write an Ecosystem File (ecosystem.config.js)

An ecosystem file keeps your process definitions inside your Git repository. It controls ports, environment variables, cluster instances, and log paths in one place.

Generate a starter template in your project’s root directory:

pm2 init simple

Open ecosystem.config.js and replace its contents with this production setup, changing script and cwd to your app’s entry file and folder:

module.exports = {
  apps: [
    {
      name: 'web-api',
      script: './dist/index.js',
      cwd: '/var/www/my-app',
      instances: 'max',
      exec_mode: 'cluster',
      autorestart: true,
      watch: false,
      max_memory_restart: '500M',
      env_production: {
        NODE_ENV: 'production',
        PORT: 3000
      },
      env_staging: {
        NODE_ENV: 'staging',
        PORT: 3001
      },
      error_file: '/var/log/pm2/web-api-error.log',
      out_file: '/var/log/pm2/web-api-out.log',
      merge_logs: true,
      time: true
    }
  ]
};

The log paths point to /var/log/pm2, so create that folder and give your deploy user write access to it:

sudo mkdir -p /var/log/pm2
sudo chown -R $USER:$USER /var/log/pm2

Start your application using the production profile:

pm2 start ecosystem.config.js --env production

pm2 list should now show one web-api row per CPU core, all online.

Step 3: Use Cluster Mode for Zero-Downtime Reloads

Node.js runs your code on a single thread by default. With exec_mode: 'cluster' and instances: 'max' in your ecosystem file, PM2 uses the native Node.js cluster module to start one worker process per CPU core.

The bigger benefit is smoother deployments. Restarting a single instance drops in-flight connections. In cluster mode, PM2 reloads workers one by one, so there is always a worker left to accept requests. Run this after each deploy:

pm2 reload ecosystem.config.js --env production

Cluster mode works best when the app keeps no state in memory between requests: store sessions in Redis or a database, not in a worker. Next.js apps follow the same pattern, as shown in the guide to deploy Next.js on a VPS.

Step 4: Set Up a systemd Startup Script for Reboots

PM2 runs in user space. If your hosting provider reboots the VPS for maintenance or a kernel patch, your processes won’t come back up on their own. You need to hook PM2 into systemd, Linux’s service manager, using systemd service definitions.

As the user that runs your app (not with sudo), generate the startup command:

pm2 startup systemd

PM2 will print a specific sudo env PATH=... command. Copy and execute the exact line from your own terminal, which looks like this:

sudo env PATH=$PATH:/usr/bin /usr/lib/node_modules/pm2/bin/pm2 startup systemd -u deployer --hp /home/deployer

Once the systemd service is active, save your currently running PM2 process list to disk:

pm2 save

This writes your active process list to ~/.pm2/dump.pm2. Whenever the server boots, the PM2 systemd service brings back every process in that dump. To check, run systemctl status pm2-YOUR_USER (for example pm2-deployer), which should show active. Then run sudo reboot, log back in, and confirm with pm2 list that your apps are online.

Run pm2 save again whenever you add or remove an app, or PM2 will restore the old list after the next reboot.

Step 5: Rotate Logs Automatically with pm2-logrotate

Node.js applications running under PM2 write stdout and stderr directly to disk. Left unchecked on a busy API, these files can grow into gigabytes and eventually use up all available disk space.

PM2 has an installable module called pm2-logrotate that rotates files automatically, compresses them with gzip, and deletes old ones.

Install the logrotate module through the PM2 CLI:

pm2 install pm2-logrotate

Once installed, set the rotation limits for production:

# Rotate logs when they hit 10 Megabytes
pm2 set pm2-logrotate:max_size 10M
# Retain the last 14 rotated log files
pm2 set pm2-logrotate:retain 14
# Compress rotated logs with gzip
pm2 set pm2-logrotate:compress true
# Rotate daily at midnight using standard cron syntax
pm2 set pm2-logrotate:rotateInterval '0 0 * * *'
# Set the rotated date format
pm2 set pm2-logrotate:dateFormat YYYY-MM-DD_HH-mm-ss

Check that your rotation rules applied cleanly:

pm2 conf pm2-logrotate

The output lists each setting with the value you just set. Rotated files appear next to the originals in /var/log/pm2 once a log passes 10 MB or the daily rotation runs.

Step 6: Set Memory Limits and Auto-Restarts

Memory leaks happen in Node.js apps. If a leak goes unchecked, the Linux kernel’s Out-Of-Memory (OOM) killer stops your process, and your reverse proxy starts returning 502 Bad Gateway errors.

Set a ceiling on memory usage so PM2 can recycle bloated workers before the kernel steps in. The max_memory_restart: '500M' line in the ecosystem file above already does this; for a process started straight from the CLI, pass the flag instead:

pm2 start server.js --name "api-service" --max-memory-restart 500M

If an individual worker creeps past 500 MB of memory, PM2 restarts that worker while the rest of the cluster continues serving traffic. Pick a limit below the RAM your VPS can actually spare per worker.

Step 7: Monitor Processes and Read Live Logs

PM2 includes an interactive terminal dashboard for watching memory, CPU load and logs across all workers.

Open the real-time terminal dashboard with:

pm2 monit

Press Ctrl+C to leave it. To tail real-time log output across all apps or scope it to a single process:

# Stream logs for all services
pm2 logs
# Stream only lines from web-api and display the last 50 entries
pm2 logs web-api --lines 50

To empty all current log files without restarting your running workers:

pm2 flush

Common Problems and Fixes

  • Apps do not come back after a reboot: you skipped the printed sudo env PATH=… command or never ran pm2 save. Repeat Step 4 and test the reboot again.
  • Missing Node binary on system reboot: If you installed Node via NVM, run pm2 startup as that user (not root) so the printed command includes the NVM bin path, and repeat pm2 unstartup and pm2 startup after every Node upgrade. Or install Node system-wide via the official NodeSource repository.
  • Environment variable caching: Running pm2 restart app-name does NOT re-read updated variables from ecosystem.config.js. After editing its env blocks, restart through the file: pm2 restart ecosystem.config.js --env production --update-env. PM2 never reads .env files itself; that is your app’s job.
  • Port collisions from orphaned processes: If your app crashes on boot claiming port 3000 is occupied, you probably have a rogue process running outside PM2. Find its PID with sudo lsof -i :3000 and stop it with kill <PID>.

Frequently Asked Questions

Why should I use PM2 instead of raw systemd service files?

Use PM2 when you want Node-specific features without writing them yourself. systemd is reliable for system services, but PM2 adds cluster load balancing, rolling reloads, live log streaming and per-process metrics. For a single, simple process, a plain systemd unit is a perfectly good choice.

Does PM2 work with TypeScript without pre-compiling?

Yes, PM2 can run TypeScript directly via ts-node. But doing that in production slows startup and uses extra RAM. Compile your TypeScript into plain JavaScript using tsc or esbuild and have PM2 run the build output.

How do I update PM2 itself?

Update the npm package, then the running daemon. Run:

sudo npm install -g pm2@latest
pm2 update

According to the official PM2 documentation, pm2 update dumps your current process state, stops the old master daemon, boots the new one, and restores your running workers. Every app is restarted once in the process, so do it in a quiet period.

Next Steps for Your VPS Stack

With PM2 clustered, monitored, and set to auto-start on boot, your Node processes recover from crashes and reboots without manual work. Next, put Nginx in front of them: the guide to an Nginx reverse proxy for Node.js WebSockets and PM2 covers the proxy settings cluster mode needs.

all_in_one_marketing_tool