PM2 keeps a Node.js application running as a managed background service instead of tying it to an SSH session. It can restart a crashed process, restore saved processes after a VPS reboot, centralize logs, and run multiple workers when your application is ready for clustering.
Antihost offers Linux VPS plans with full root access, unlimited traffic on a 1 Gbps port and a 14-day free trial.
The reliable workflow is: install PM2 globally, start each app with a stable name, verify its state, put repeatable settings in an ecosystem file, configure boot-time startup, save the process list, and monitor logs and restarts. The sections below show the commands, configuration, trade-offs, and recovery steps.
As an Amazon Associate I earn from qualifying purchases.
The Tool Desk
Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →What PM2 does on a VPS
Node.js normally runs in the foreground. If you launch node app.js from an SSH shell, the process may end when the session closes, and it will not automatically return after a crash or a server reboot. PM2 adds a daemon that supervises one or more Node.js processes. As the PM2 documentation puts it, “PM2 is a daemon process manager that will help you manage your application online.”
PM2 is not a replacement for application health checks, backups, a firewall, or a reverse proxy. It is the process layer between your application and the operating system. You still need to secure the VPS, keep Node.js and dependencies patched, expose only the ports you intend to expose, and decide how TLS, domains, and request routing are handled.
#1 Best Overall
- [Ultra-Lightweight Ear Buds Designed for Small Ears] Each earbud weighs only 3.7g and features a compact, ergonomic in-ear design made especially for small ears. Secure, low-profile, and comfortable for workouts, all-day wear or overnight sleeping.The ultra-slim profile sits flush in your ear with no hard edges poking or rubbing, so you can even sleep on your side without discomfort.
- [Immersive Stereo Sound with TOZO OrigX Technology] TOZO OrigX tuning delivers clear vocals, balanced mids, and natural stereo sound for music, podcasts, and videos.
- [Long Battery Life for Daily Use] Get up to 7 hours of playtime on a single charge, with up to 32 hours total using the charging case—ideal for workdays, commuting, and extended listening sessions.
- [Bluetooth 5.3 & Stable Connection] Bluetooth 5.3 provides fast pairing, stable wireless performance, and reduced dropouts as you move around home or office.
- [Deep Bass with Clear Vocals] High-performance drivers produce punchy bass while keeping vocals clean and detailed for everyday listening.
What PM2 can and cannot guarantee
- It can restart a process that exits and keep a named process list for routine operations.
- It can restore the process list at boot after you configure startup integration and save the list.
- It can collect standard output and error output and show process status in a terminal dashboard.
- It does not make in-memory sessions or caches shared between workers.
- It does not provide a universal uptime guarantee or a single performance number that applies to every VPS and Node.js application.
Prerequisites and a safe deployment layout
You need a VPS account with shell access, a supported Node.js installation, npm (or Yarn), the application source, and permission to install a global npm package and configure a boot service. Run application processes as a dedicated non-root user whenever your hosting setup allows it. Reserve root or sudo for system packages and the command generated by PM2 startup.
Choose a predictable application directory, for example /srv/apps/orders-api, and make that directory the deployment user’s working directory. Keep the source, lockfile, ecosystem file, and operational notes together. Do not commit private keys, database passwords, API tokens, or other secrets to the repository.
Check Node.js and npm before installing PM2
node --version
npm --version
pwd
The first two commands confirm that the shell used for deployment can find the same Node.js installation that PM2 will later use. This matters when Node.js was installed with a version manager: the interactive SSH shell and the boot service may otherwise resolve different paths.
Install PM2 and start your first app
Install the current PM2 package
Install PM2 globally with npm so the pm2 command is available to the deployment user:
npm install pm2@latest -g
pm2 --version
Yarn can be used instead if it is the package manager in your deployment workflow. Keep the installation method consistent for the user who owns the applications and for the Node.js path used by the startup service.
Start a Node.js entry point with a stable name
Change to the application directory and start the entry script. The name is important: it makes later commands unambiguous, especially when several applications use similarly named files.
Quick wins for a faster PC:
Scan for outdated or missing drivers - takes under a minuteDriver Scan →Repair Windows errors before they cause bigger problemsFix Now →Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →cd /srv/apps/orders-api
pm2 start app.js --name orders-api
If the application needs arguments, put them after -- so PM2 does not interpret them as its own options:
Rank #2
- 【IP68 Waterproof Multifunctinal Smart Watch】Torjalph fitness activity tracker smart watch is IP68 waterproof technology ,you can wear it when swimming,handwashing,it's rain-proof which means that you perform multiple exercise modes outside without worrying about sweat or rain corroding your fitness smart watch,and this watch equipped with a 230 mAh large capacity battery magnetic charging ,and this sports activity tracker watch can be used 5-7 days If fully charged.
- 【Larger 1.83'' Full Screen Watch & Multi-dial Selection】1.83 inch full HD color touch screen smart watch for men / women provides excellent 240*284 resolution image quality ,This Bluetooth smart watch offers a better touch experience and remarkable immersion and ,more than 200 watch faces for you to choose from App"Da Fit ", you can change the dial style according to your mood to wear keeping the world on your wrist
- 【Accurate Activity Tracker Smart Watch 】sports watch activity tracker uses sweat and dust resistant breathable silicone strap, our Fitness Tracker Smart Watch for Android iOS Phones supports 12 sports modes,walking,running,bicycle,swimming,badminton,basketball,football,rope skipping. This bluetooth calls smart watch for men women is lightweight and stylish, bringing more convenient and relaxing sports experience while also providing more protection.
- 【Your 24 Hour Personal Daily Health Monitor】Fitness watch for women men full touch screen IP67 waterproof bluetooth smartwatch for Android iOS Phones with heart rate blood pressure monitor multifunction Andriod smart watch with steps counter sleep monitor sports fitness watch, monitoring blood oxygen saturation allows you to understand your physical condition in real time to track fitness progress ,to know your health status in time.
- 【More Functions Bluetooth Call Smart Watch】This fitness activity smart watch full screen for iPhone and Android phones includes a bunch of new features including:The bluetooth smart watch can hang up the phone, receive and display WhatsAPP /Text /Facebook /Twitter /Messenger reminder.Support sedentary reminder, alarm clock, stopwatch, timer,weather information,music control, remote camera control compatible with Android 5.0 and above or iOS 9.0 and above smartphones.
pm2 start app.js --name orders-api -- --port 3000
For a package that defines its own start script, start the package manager command explicitly and preserve the process name:
pm2 start npm --name orders-api -- start
Verify that PM2 owns the process
pm2 list
pm2 ls
pm2 status
These aliases display the process name, identifier, mode, status, restart count, uptime, CPU, and memory columns. A status of online means PM2 believes the process is running; it does not prove that a health endpoint, database connection, or user-facing request succeeds. Test the application separately from the VPS, or query its local health endpoint.
PM2 lifecycle commands you will use every day
Use the stable name rather than a numeric identifier in scripts and runbooks. Numeric IDs can change when processes are deleted and recreated.
Free tools Windows power users keep installed
One-click scans. No signup required.
| Operation | Command | Use it when |
|---|---|---|
| Show all processes | pm2 status |
You need a quick state and restart-count check. |
| Show live output | pm2 logs orders-api |
You are diagnosing current requests or errors. |
| Restart | pm2 restart orders-api |
You need to stop and start the process, accepting a brief interruption if the app is single-process. |
| Reload | pm2 reload orders-api |
The app runs in cluster mode and can replace workers with reduced downtime. |
| Stop | pm2 stop orders-api |
You need the process kept in PM2’s list but not running. |
| Delete | pm2 delete orders-api |
You are removing the process from PM2’s managed list. |
After changing source files, dependencies, environment variables, or ecosystem settings, use the operation that matches the change. A normal restart is not the same as a cluster reload, and deleting a process removes it from the list that will be saved for boot.
Use an ecosystem file for repeatable configuration
An ecosystem file turns a collection of command-line choices into version-controlled configuration. Generate a starter file with either command:
pm2 ecosystem
# or
pm2 init simple
Then edit the generated JavaScript file. The following example shows two services and the principal options PM2 supports. Adjust paths, names, ports, and instance counts to your deployment rather than copying them unchanged.
module.exports = {
apps: [
{
name: "orders-api",
script: "./app.js",
cwd: "/srv/apps/orders-api",
args: "--port 3000",
instances: 1,
exec_mode: "fork",
env: {
NODE_ENV: "development"
},
env_production: {
NODE_ENV: "production",
PORT: 3000
},
max_memory_restart: "500M",
watch: false,
ignore_watch: ["node_modules", "logs"],
error_file: "/var/log/pm2/orders-api-error.log",
out_file: "/var/log/pm2/orders-api-out.log",
merge_logs: true,
wait_ready: true,
listen_timeout: 10000,
kill_timeout: 5000
},
{
name: "worker",
script: "./worker.js",
cwd: "/srv/apps/orders-worker",
instances: 1,
exec_mode: "fork",
env_production: {
NODE_ENV: "production"
},
max_memory_restart: "400M",
watch: false,
error_file: "/var/log/pm2/worker-error.log",
out_file: "/var/log/pm2/worker-out.log"
}
]
};
Start an ecosystem file for production
If the file contains an env_production block, select it explicitly:
Rank #3
- [Low Noise High Fidelity] New bee guitar cord with 22AWG oxygen-free-copper center conductors provides enhanced signal transfer, the PVC insulation material and the high-density stranded copper double shield provide noise rejection for quiet operation
- [Ideal for Choice] New bee 1/4 straight and right angle metal connectors, ensures a secure connection in any instrument, pedal, or amp jack. L shape great fro on stage guitar stands
- [Wide Compatible] Suitable for mixer, power amplifier, microphone, effector, decoder, equalizer, electoronic organ, electric guitar, electric bass and other electronic equipments. Widely used in the installation of smart home, karaoke speaker, professional stage audio, etc
- [Easy Disassemble] Making incidental repairs quick and easy! Very nice, flexible cable
- [Dont Hesite to Order] 24 hours customer services and professional technology team are standing by
pm2 start ecosystem.config.js --env production
Without --env production, PM2 uses the default env block when one exists. Confirm the resulting variables in the application’s startup diagnostics, but never print secret values into logs.
What the important options control
scriptandcwd: identify the entry point and the directory from which relative paths are resolved.nameandargs: provide an operational label and application arguments.instancesandexec_mode: select one or more processes and fork or cluster behavior.envandenv_production: define environment variables for the selected environment.max_memory_restart: ask PM2 to restart a process when its observed memory exceeds the configured threshold. This is a safety valve, not a substitute for finding a leak.watchandignore_watch: restart on file changes when appropriate, while excluding directories such as dependencies, generated files, and logs. Disable watch for ordinary production deployments unless you have a deliberate reason to use it.error_file,out_file, andmerge_logs: define where output goes and whether workers share a combined output stream.wait_ready,listen_timeout, andkill_timeout: coordinate readiness and shutdown timing during controlled replacements.
Keep secrets out of the ecosystem file
Environment-variable configuration is supported, but a committed ecosystem file should contain only non-sensitive defaults. Inject credentials through the VPS environment or a secrets mechanism provided by your organization. Restrict file permissions, avoid displaying the environment in diagnostic output, and rotate credentials independently of application code.
Make PM2 survive SSH disconnects and reboots
Starting a process with PM2 detaches it from your terminal, but a reboot still clears running processes unless you configure boot integration. Perform these steps after the final process list is correct:
- Ask PM2 to generate the startup integration command:
pm2 startup - Copy and execute the complete command PM2 prints. It normally requires elevated privileges; the exact command depends on the operating system, user, and Node.js installation path.
- Save the current managed process list:
pm2 save - Reboot during a maintenance window, then reconnect and verify:
pm2 status pm2 logs --lines 200
Saving before the process list is correct can restore an unwanted or broken service at every boot. After adding, deleting, or renaming applications, run pm2 save again so the boot snapshot matches the intended state.
NVM and Node.js path changes
When Node.js is managed with NVM, its installation path can change after switching versions. The startup service may continue pointing at the old path. Rerun pm2 startup, execute the newly generated privileged command, and save the process list again after a Node.js version change. Test a reboot rather than assuming an interactive shell’s node command represents the boot environment.
Logs, monitoring, and restart diagnosis
Read recent output without flooding the terminal
pm2 logs orders-api
pm2 logs orders-api --lines 200
Use the unbounded stream while reproducing a problem and the bounded form when you need recent context. PM2 separates standard output and error output according to the configured files, or uses its defaults when no paths are supplied.
Use the terminal dashboard
pm2 monit
The dashboard helps you correlate CPU, memory, restarts, and output across processes. A rising restart count usually deserves an application-level investigation: inspect the error log, run the entry point in the same working directory, verify environment variables, and check that required services are reachable.
Rank #4
- Digital Family Calendar: BSIMB digital calendar wall touch screen puts an end to your chaotic life. Designed for busy families, the digital calendar keeps you organised and in step with your family. Assign different colours and tasks to each family member to make family scheduling easier and more intuitive.
- Easy Setup and Auto-Sync: Plug in, connect to WLAN and auto-syn your electric calendar in minutes. Digital wall calendar compatible with Google calendar, iCloud calendar, Outlook calendar, Cozi calendar and Yahoo calendar. Add events directly on the device or through the ecalendar app. Electronic calendar stays current whether you're at work or traveling—no manual updates needed.
- All-In-One Home Assistant: Smart calendar builds habits and encourage independence with personalised chores. Display daily meal plan to reduce the daily ‘What's for dinner?’ stress. To-do lists keep track of everything you want. Turning chores into valuable achievements with stars and rewards, making life easier and more enjoyable.
- Manage Anytime Anywhere: BSIMB electronic calendar for family stay connected with the powerful ecalendar app. Access and manage your digital wall calendar anytime, anywhere with free features like stars & rewards, photo screensaver, chore charts, meals plans, to-do lists etc. Electronic planner paid features like Magic Import tailor advanced tools for users with special needs.
- Stay in Touch with Loved Ones: Share photos or videos from your phone to electronic wall calendar with app, instantly update your life moment, and keep in touch with your family, especially those who are far away; you can also surprise your smart calendar digital wall by sending him a wish card; it's also great for keeping tech-illiterate elders in touch with the youngsters.
Prevent unbounded log growth
Log files can fill a VPS even when the application remains healthy. Choose explicit output and error paths, ensure the PM2 user can write them, and establish a rotation and retention policy using the operating system or your organization’s logging system. Rotation should preserve recent history for incident analysis while deleting or archiving old files before disk space becomes critical. PM2’s process status is not a substitute for disk-space monitoring.
Fork mode versus cluster mode
Fork mode runs the configured application as an ordinary independent process. It is the simplest choice for stateful services, background workers, development, and applications that are not designed for multiple concurrent workers.
Cluster mode starts multiple Node.js workers and distributes supported connections among them. PM2 cluster mode can distribute HTTP, HTTPS, WebSocket, TCP, and UDP connections. You can request the maximum suitable worker count with:
pm2 start app.js --name orders-api -i max
Or set instances and exec_mode: "cluster" in the ecosystem file.
| Axis | Fork mode | Cluster mode |
|---|---|---|
| Process count | Usually one process per app entry | Multiple workers managed as one application |
| Statefulness | Worker-local memory stays in that process | Worker-local memory is not synchronized automatically; externalize shared state |
| Reload behavior | A restart normally interrupts the single process | pm2 reload can replace workers progressively to reduce interruption |
| CPU utilization | One worker cannot use all available CPU cores for one event loop | Several workers can use more cores when the workload and application design justify it |
| Operational complexity | Lower; easier debugging and simpler failure analysis | Higher; requires readiness, graceful shutdown, shared-state design, and worker-aware logging |
| Logs | One output and error stream per configured process | Multiple worker streams; use clear file names or merged logs and include worker context in application logs |
Check statefulness before clustering
Do not enable cluster mode merely because the VPS has several CPU cores. Sessions stored in process memory, local caches, in-memory queues, open files, and singleton assumptions can behave differently when requests reach different workers. Put sessions, queues, and other shared state in an external service or design the application so requests are independent. Verify WebSocket connection handling and shutdown behavior with more than one worker.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Safe reloads and graceful shutdown
A reload is only as safe as the application’s lifecycle code. On shutdown, stop accepting new work, finish or cancel in-flight operations within a bounded time, close database and message-broker connections, and then exit. If your application uses PM2 readiness signaling, enable wait_ready and send the ready event only after the server is actually accepting requests.
const http = require('http');
const app = require('./app');
const port = Number(process.env.PORT || 3000);
const server = http.createServer(app);
server.listen(port, () => {
if (process.send) process.send('ready');
});
let shuttingDown = false;
async function shutdown(signal) {
if (shuttingDown) return;
shuttingDown = true;
console.log(`${signal}: shutting down`);
server.close(async () => {
// Close database, queue, and other client connections here.
process.exit(0);
});
setTimeout(() => process.exit(1), 5000).unref();
}
process.on('SIGINT', () => shutdown('SIGINT'));
process.on('SIGTERM', () => shutdown('SIGTERM'));
Set listen_timeout long enough for a normal worker to become ready and kill_timeout long enough for expected cleanup, but not so long that a wedged worker blocks deployment indefinitely. Test the actual behavior with a staging reload and with a request in flight.
Best Value
Direct Node exposure or a reverse proxy?
PM2 can keep a Node process alive while it listens on a port, but many production deployments place a reverse proxy in front of it. The proxy decision is separate from PM2 and depends on your domain, TLS, routing, and observability requirements.
Recommended Free Tools
| Concern | Direct Node exposure | Reverse proxy in front |
|---|---|---|
| TLS termination | Node handles certificates and HTTPS directly | Proxy commonly handles certificates and forwards internal traffic |
| Routing | Each app generally needs its own exposed port | Hostnames or paths can route to several internal ports |
| Port exposure | Application port is reachable wherever the firewall permits | Only the proxy’s public ports need to be exposed; app ports can remain private |
| Buffering and limits | Implemented in Node and its framework | Proxy can provide request buffering, body limits, and connection policy |
| Observability | Application logs contain request details if implemented | Proxy access logs can be correlated with PM2 and application logs |
Whichever arrangement you choose, make the application’s bind address, forwarded headers, health checks, and timeout settings explicit. PM2 does not configure those network policies for you.
Deployment routine for updates
- Deploy the new source and lockfile into the application directory or a new release directory.
- Install the exact dependency versions required by the lockfile.
- Run migrations or other one-time tasks deliberately and verify their result.
- Check the ecosystem file, working directory, environment selection, and file permissions.
- For a single forked process, use
pm2 restart app-nameduring an accepted maintenance window. For a correctly designed cluster, usepm2 reload app-name. - Watch
pm2 statusandpm2 logs app-name --lines 200for startup errors, repeated restarts, and failed readiness. - After adding or removing managed services, run
pm2 saveso a future reboot restores the intended list.
Keep rollback simple: retain the previous known-good release, record which ecosystem configuration was active, and be able to point cwd or the symlink used by the service back to it. Do not delete the only copy of a working release until the new version has passed its health checks.
Troubleshooting common PM2 failures
The app stops when I close SSH
Check that it was started through PM2 rather than directly with node. Run pm2 status, then inspect pm2 logs app-name. If PM2 itself is absent after logout, confirm you installed it for the same user that owns the application and that you did not rely on a terminal multiplexer as a substitute for process supervision.
The app does not return after a reboot
Run pm2 startup and execute the complete generated command with the required privileges. Then run pm2 save. If Node.js uses NVM or another version manager, regenerate startup integration after path changes. Examine the operating system’s service status and PM2 logs from a fresh login.
Outdated Drivers Are Slowing You Down
One free scan finds every outdated or missing driver and matches the right update for your exact hardware.Free scan · exact hardware matchWindows Errors? Fix Them Before They Spread
Repair common Windows errors and clear accumulated junk for a smoother, more stable PC - no reinstall needed.Free scan · no reinstallPM2 reports online but requests fail
Confirm the process is listening on the expected port and address, that the firewall allows the intended traffic, and that a reverse proxy points to the same port. Test the local health endpoint from the VPS, then inspect application errors rather than treating the online label as an HTTP health check.
The process restarts repeatedly
Use pm2 status to note the restart count and read the error output. Common causes include a syntax error, missing environment variable, unavailable database, wrong cwd, permission failure, or a memory limit that is too low. Run the entry command manually from the configured working directory with the same non-secret environment to reproduce the failure.
Reload causes dropped requests or never completes
Check that workers signal readiness only after binding their listening socket, and that shutdown handlers close resources promptly. Increase listen_timeout or kill_timeout only when measured startup or cleanup time justifies it. A reload cannot make an application safe if it keeps mutable state only in worker memory or ignores termination signals.
Logs are missing or the disk is full
Verify the configured directory exists and is writable by the PM2 user. Check the effective out_file and error_file values, inspect disk usage, and implement rotation and retention. After correcting paths or permissions, restart the affected process and generate a test line so you know the complete pipeline works.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
Quick Recap
Operational checklist
- Install PM2 globally for the deployment user and confirm its version.
- Start every service with a unique, stable
--name. - Use
pm2 statusand an application health check after startup. - Store scripts, working directories, environment blocks, limits, and log paths in an ecosystem file.
- Keep secrets outside committed configuration.
- Run
pm2 startup, execute its generated privileged command, and runpm2 save. - Repeat startup setup after Node.js path changes, especially with NVM.
- Define log destinations and rotation before production traffic arrives.
- Choose cluster mode only after externalizing shared state and testing graceful shutdown.
- Use reloads for properly prepared clusters; use restarts when a full stop-and-start is intentional.
- Monitor restart counts, memory, CPU, error output, and disk space.
- Test reboot recovery and rollback while you still have a known-good release.
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.




