Node js pm2 windows

PM2 is “…a production process manager for Node.js applications with a built-in load balancer. It allows you to keep applications alive forever, to reload them without downtime and to facilitate common system admin tasks…”.

I use PM2 to run and monitor Express apps. Below is a quick list of steps I follow to install PM2 (version 4.2.3 at time of writing) on Windows and run as a Windows service, tested on Windows Server 2016.

Implied is my “works for me” disclaimer at the bottom of this post — these steps are not the only or best way to install PM2 on Windows, but work for me and might hopefully be useful to someone else :-)

  1. create a local administrator on the Windows server e.g. PM2Admin

  2. log in as the local administrator (all the steps below are performed as as the local administrator created in step 1 unless specified)

    • why? as at early 2020, installing globally using npm saves to a user’s profile. I’ve found it best to log in as that specific user to perform all PM2 actions.
  3. if not already done, install Node.js

  4. from a command prompt (may need to be an administrative command prompt depending on how the Windows server is set up), install PM2 globally as per https://pm2.io/doc/en/runtime/guide/installation: npm install -g pm2

  5. create a PM2 directory, for example C:\pm2

  6. create an environment variable “PM2_HOME” pointing at directory created in step 5 (e.g. C:\pm2) as per https://blog.cloudboost.io/nodejs-pm2-startup-on-windows-db0906328d75

  7. restart the server, log in again as the local administrator created in step 1

  8. test PM2 by running pm2 save from a command prompt before installing the Windows service below

  9. as per https://blog.cloudboost.io/nodejs-pm2-startup-on-windows-db0906328d75, from a command prompt, install pm2-windows-service globally: npm install -g pm2-windows-service

  10. if there’s issues installing or running pm2-windows-service, may need to update old dependency as per https://github.com/jon-hall/pm2-windows-service/issues/51#issuecomment-532066926

  11. from a command prompt, run pm2-service-install -n PM2, and answer questions as below:

    ? Perform environment setup (recommended)? Yes
    ? Set PM2_HOME? Yes
    ? PM2_HOME value (this path should be accessible to the service user and should not contain any “user-context” variables [e.g. %APPDATA%]): C:\pm2
    ? Set PM2_SERVICE_SCRIPTS (the list of start-up scripts for pm2)? No
    ? Set PM2_SERVICE_PM2_DIR (the location of the global pm2 to use with the service)? [recommended] Yes
    ? Specify the directory containing the pm2 version to be used by the service C:\USERS\<USER>\APPDATA\ROAMING\NPM\node_modules\pm2\index.js
    
  12. a Windows service called “PM2” should now be configured and can be managed & started using Services Manager

  13. reminder: files in the C:\pm2 directory should not be edited

  14. (optional) can install PM2 log rotate module from a command prompt (see https://github.com/keymetrics/pm2-logrotate for more info): pm2 install pm2-logrotate

  15. may need a process to clean up PM2 log rotate logs themselves, such as the following PowerShell snippet:

Get-ChildItem -Path 'C:\pm2\logs\*' -Include 'pm2-logrotate-out__*.log' | Where-Object { $_.LastWriteTime -lt (Get-Date).AddMonths(-1) } | Remove-Item

Thomas’s “but it worked for me” disclaimer: before using any code you find on the internet, especially on this blog, take time to understand what the code does and test, test, test. I’m not responsible for damage caused by code from this blog, and don’t offer any support or warranty.

WINDOWS

Introduction

PM2 is a powerful process manager for Node.js applications, designed to ensure that your applications run seamlessly in production environments. Utilizing PM2 allows developers to manage application processes efficiently, handle automatic restarts, monitor performance, and even manage clusters of Node.js applications. However, one of the major limitations of PM2 is that it lacks built-in support for automatic startup on Windows. This article will provide a comprehensive guide to running PM2 as a service on Windows Server, ensuring that your Node.js applications are always up and running, even after a reboot.

Why Use PM2?

Before delving into the setup process, it is essential to understand the benefits of using PM2 for managing Node.js applications:

  • Automatic restarts on application failure.

  • Load balancing with the built-in cluster mode.

  • Real-time monitoring and logging with the PM2 dashboard.

  • Process management for multiple applications.

  • Easy deployment with processes defined in a JSON configuration file.

Installing PM2

Before you can run PM2 as a service, you must install it. Here’s how to do this on a Windows Server:

Step 1: Install Node.js

  1. Download the latest Windows installer for Node.js from the official website: Node.js Downloads.

  2. Run the installer and follow the instructions to complete the installation.

  3. After installation, verify by running the following command in a Command Prompt:

Step 2: Install PM2 Globally

Once Node.js is installed, you can install PM2 globally using npm:

Confirm the installation by checking the PM2 version:

Setting Up PM2 to Run as a Windows Service

To ensure that PM2 runs as a service on your Windows Server, you will need to use a utility called NSSM (Non-Sucking Service Manager). NSSM is an excellent tool for managing services on Windows.

Step 1: Download NSSM

  1. Go to the NSSM download page: NSSM Downloads.

  2. Download the ZIP file corresponding to your system architecture (32-bit or 64-bit).

  3. Extract the downloaded file to a directory on your server, e.g., C:\nssm-2.xx\.

Step 2: Create a PM2 Service Using NSSM

  1. Open a Command Prompt with administrative privileges (Run as Administrator).

  2. Navigate to the directory where you extracted NSSM:

   cd C:\nssm-2.xx\win64  # or win32 if you're on a 32-bit OS
  1. Create a new service for PM2:

  1. A GUI will open. Fill in the details as follows:

    • Path: The path to the Node.js executable. This typically looks like:

      
      C:\Program Files\nodejs\node.exe
      
    • Startup directory: The path where you want PM2 to start. Usually, this can be your Node.js project directory.

    • Arguments: Enter the following command to start PM2:

      
      C:\Users\YourUsername\AppData\Roaming\npm\pm2.cmd start C:\path\to\your\app.js --name your-app-name
      
  2. Click Install service to create the PM2 service.

Step 3: Start the PM2 Service

To verify that the service has been created and start it, use the following command:

You can also check the status of the service with:

Configure PM2 for Automatic Start on Reboot

Now that PM2 is set up as a service, you need to ensure that it starts automatically when the server boots up:

  1. Open the NSSM service GUI again by running:

  1. In the GUI, navigate to the Details tab and ensure that the service is set to Automatic in the Startup type dropdown.

  2. Click OK to save the changes.

Managing Your Applications with PM2

Once PM2 is running as a service, you can manage your applications effortlessly. Here are a few useful PM2 commands:

  • Start an application:

    pm2 start app.js --name your-app-name
    
  • Stop an application:

  • Restart an application:

    pm2 restart your-app-name
    
  • List all running applications:

  • Monitor application logs:

Troubleshooting Common Issues

  • PM2 fails to start after a reboot: Ensure that NSSM is properly configured for automatic startup and that all paths are accurate.

  • Applications not responding: Check the PM2 logs for any error messages using pm2 logs.

  • Service not found: Ensure that you have installed the PM2 service correctly using NSSM.

Conclusion

By following the steps outlined in this article, you can run PM2 as a service on your Windows Server efficiently and modernly. Automating your Node.js application management not only saves time but also boosts reliability and performance. Whether you are an individual developer or part of a larger team, leveraging PM2 for process management is a strategic approach to ensure your applications remain robust and performant.

For further reading, explore the official PM2 documentation and consider more advanced configurations such as clustering and performance monitoring.

Suggested Articles

WINDOWS

WINDOWS

WINDOWS

WINDOWS

WINDOWS

WINDOWS

Today I gonna share with you guys how to auto start PM2 with Node Application on Windows after reboot? For this approach, we will use this pm2-windows-service module to achieve this.

1. Configure the PM2

npm i -g pm2
  • Copy C:\Users\<Windows-Username>\.pm2 folder to C:\etc\.pm2
  • Add a new system variable name: PM2_HOME and value: c:\etc\.pm2

2. Start and Save your new node application with PM2

pm2 start server.js --name server 
pm2 save

3. Install the PM2 windows service

npm install -g @innomizetech/pm2-windows-service
pm2-service-install -n PM2

4. Set the following parameters

– Perform environment setup (recommended)? Y
– Set PM2_HOME? Y
– PM2_HOME value (this path should be accessible to the service user and
should not contain any “user-context” variables [e.g. %APPDATA%]): c:\etc\.pm2\
– Set PM2_SERVICE_SCRIPTS (the list of start-up scripts for pm2)? N
– Set PM2_SERVICE_PM2_DIR (the location of the global pm2 to use with the service)? [recommended] Y
– Specify the directory containing the pm2 version to be used by the
service C:\USERS\\APPDATA\ROAMING\NPM\node_modules\pm2\index.js Press Enter

PM2 service installed and started.

That’s it. I hope this will help. ?
Photo: https://www.brandeps.com

I am a seeker of knowledge and also coincidentally a Software Engineer.
View all posts by Nay Zaw Lin

Installation

Install pm2

With yarn:

With npm:

With debian, use the install script:

apt update && apt install sudo curl && curl -sL https://raw.githubusercontent.com/Unitech/pm2/master/packager/setup.deb.sh | sudo -E bash -

With docker, follow this tutorial.

CLI autocompletion

By default, CLI autocompletion is not installed with PM2, we recommend it:

Source map support

Source map files are autodetected by default if they are present (app.js.map for app.js).

What are source map files? If using Babel, Typescript or any other Javascript superset, you may have noticed that stacktraces are not meaningful, errors not pointing to the right line. Source map files can be used to solve this problem.

Update

Keep your pm2 up to date with:

npm install pm2 -g && pm2 update

pm2 update is necessary in order to refresh the PM2 daemon.

Next Steps

Ecosystem File

  • PM2 is a Process Manager for NodeJS and IOJS application in production environment.
  • PM2 supports Express,Hapi,Geddy and Sail etc framework for NodeJS based web application.
  • PM2 helps the application to run forever,reload application without downtime and common admin tasks
  • In this Demo, “We will learn to install,configure the PM2 in Window”.
  • PM2 module can be installed using npm install pm2 –save-dev command.The following screenshot shows the terminal with PM2 installation.

image

  • We can also install the PM2 module globally using npm install pm2 –g command.The following screenshot shows the terminal with PM2 global installation.

image

  • To demonstrate PM2 we have created a project named PM2Demo application.The structure of PM2Demo is as follows:-
  • The server.js file contains code for dummy application.The code content of server.js are as follows:-
var http = require('http'),
    server = http.createServer(function(request,response){
        response.end("Response From Node Server");
    });
server.listen(3000, function(){
    console.log("Server started at port: 3000");
});
  • The server.js file can be run using node server.js command .The following screenshot shows the terminal with server.js in execution.

image

  • The output of this demo will look like following screenshot:-

image

  • Now we can configure PM2 in Windows using some DOS command. The following screenshot shows NodeJS command prompt CLI opened in Administrative mode with DOS command executed:-

image

  • We can start the server.js file using pm2 start server.js command.The following screenshot shows the pm2 command in execution.

image

  • In upcoming posts we will learn more about PM2.Till then stay tuned.
  • The demo code can be downloaded from the following URL:-

https://github.com/saan1984/PM2Demo

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Windows не удается подключиться к принтеру 0x0000000a windows
  • Компьютер долго включается что делать для windows 10
  • Параметры мыши в windows 10 по умолчанию
  • Не играют колонки на компьютере windows 10
  • Как посмотреть дамп памяти windows 11