pm2 README

The project's README from github.com/Unitech/pm2. As one markdown file: README.md.


PM2

P(rocess) M(anager) 2
Runtime Edition

Downloads per Month Downloads per Year npm version


PM2 is a production process manager for Node.js/Bun 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.

Starting an application in production mode is as easy as:

$ pm2 start app.js

PM2 is battle-tested by a comprehensive test suite.

Official website: https://pm2.keymetrics.io/

Works on Linux, macOS, and Windows. Supports Node.js 18+ and Bun 1+.

Installing PM2

With NPM

$ npm install pm2 -g

With Bun

$ bun install pm2 -g

If you only have Bun installed (no Node.js), symlink node to bun so PM2's #!/usr/bin/env node shebang resolves to Bun's node-compatibility runtime:

$ sudo ln -s $(which bun) /usr/local/bin/node

You can install Node.js easily with NVM or FNM or install Bun with curl -fsSL https://bun.sh/install | bash

Start an application

You can start any application (Node.js, Bun, and also Python, Ruby, binaries in $PATH...) like that:

$ pm2 start app.js
$ pm2 start app.ts
$ pm2 start app.py

Your app is now daemonized, monitored and kept alive forever.

Managing Applications

Once applications are started you can manage them easily:

Process listing

To list all running applications:

$ pm2 list

Managing apps is straightforward:

$ pm2 stop     <app_name|namespace|id|'all'|json_conf>
$ pm2 restart  <app_name|namespace|id|'all'|json_conf>
$ pm2 delete   <app_name|namespace|id|'all'|json_conf>

To have more details on a specific application:

$ pm2 describe <id|app_name>

To monitor logs, custom metrics, application information:

$ pm2 monit

More about Process Management

Cluster Mode: Node.js Load Balancing & Zero Downtime Reload

Cluster mode starts multiple Node.js processes and load-balances HTTP/TCP/UDP queries between them. This significantly increases throughput on multi-core machines and improves reliability (faster socket re-balancing in case of unhandled errors).

Framework supported

Starting a Node.js application in cluster mode that will leverage all CPUs available:

$ pm2 start api.js -i <processes>

<processes> can be 'max', -1 (all cpu minus 1) or a specified number of instances to start.

Zero Downtime Reload

Hot Reload allows you to update an application without any downtime:

$ pm2 reload all

More information about how PM2 makes clustering easy

Container Support

With the drop-in replacement command for node, called pm2-runtime, run your Node.js application in a hardened production environment. Using it is seamless:

RUN npm install pm2 -g
CMD [ "pm2-runtime", "npm", "--", "start" ]

Read More about the dedicated integration

Terminal Based Monitoring

Monit

Monitor all processes launched straight from the command line:

$ pm2 monit

Log Management

To consult logs just type the command:

$ pm2 logs

Standard, Raw, JSON and formatted output are available.

Examples:

$ pm2 logs APP-NAME       # Display APP-NAME logs
$ pm2 logs --json         # JSON output
$ pm2 logs --format       # Formatted output

$ pm2 flush               # Flush all logs
$ pm2 reloadLogs          # Reload all logs

To enable log rotation install the following module

$ pm2 install pm2-logrotate

More about log management

Startup Scripts Generation

PM2 can generate and configure a Startup Script to keep PM2 and your processes alive at every server restart.

Init Systems Supported: systemd, upstart, systemv, openrc, launchd, rcd, rcd-openbsd, smf

# Generate Startup Script
$ pm2 startup

# Freeze your process list across server restart
$ pm2 save

# Remove Startup Script
$ pm2 unstartup

More about Startup Scripts Generation

Updating PM2

# Install latest PM2 version
$ npm install pm2@latest -g
# Save process list, exit old PM2 & restore all processes
$ pm2 update

PM2 updates are seamless

PM2+ Monitoring

If you manage your apps with PM2, PM2+ makes it easy to monitor and manage apps across servers.

https://app.pm2.io/

Feel free to try it:

Discover the monitoring dashboard for PM2

Thanks in advance and we hope that you like PM2!

CHANGELOG

CHANGELOG

Contributors

Contributors

License

PM2 is made available under the terms of the GNU Affero General Public License 3.0 (AGPL 3.0). For other licenses contact us.

pm2 (Unitech/pm2)

Searching Database…

43.3K ·GitHub
Что это такое?PM2 — это менеджер процессов для продакшена в приложениях на Node.js и Bun. Он поддерживает их работу постоянно, перезагружает без простоя и включает встроенный балансировщик нагрузки.
Это библиотека, которую я импортирую, или самостоятельная CLI-утилита?Это самостоятельная CLI-утилита, которую вы запускаете рядом с вашим приложением, а не библиотека для импорта в код. Её устанавливают глобально, а для управления процессами используют команды вроде pm2 start.
Как запустить приложение под PM2?Установите PM2 через npm, затем выполните pm2 start для входного файла вашего приложения (Node.js, Bun, Python, Ruby или любой бинарный файл из $PATH). Процесс сразу уходит в фон и поддерживается в рабочем состоянии.
Нужен ли мне Node.js или можно обойтись только Bun?PM2 требует Node.js 18+ или Bun 1+. Если установлен только Bun, нужно создать символическую ссылку node на bun, чтобы shebang PM2 с node корректно разрешался.
Режим кластера работает для любого типа приложений?Режим кластера предназначен именно для приложений на Node.js: он распределяет нагрузку HTTP/TCP/UDP между несколькими процессами, используя все ядра процессора. Приложения на других языках запускаются как обычные управляемые приложения с одним процессом.
На каких операционных системах это работает?PM2 работает на Linux, macOS и Windows.
Что такое панель PM2+ и она обязательна?PM2+ — это отдельная облачная панель мониторинга и управления приложениями, запущенными через PM2 на нескольких серверах. Это необязательное дополнение, для работы самого PM2 оно не нужно.
Может ли PM2 автоматически перезапускать мои приложения после перезагрузки сервера?Да, он может создать стартовый скрипт для systemd, upstart, systemv, openrc, launchd и других систем инициализации, чтобы PM2 и ваши процессы запускались заново при каждой перезагрузке сервера.
Как отслеживать логи, загрузку процессора и памяти из терминала?PM2 включает встроенное мониторинг-представление в терминале и команды для логов, которые поддерживают стандартный, сырой, JSON и форматированный вывод.
Можно ли использовать PM2 внутри контейнеров Docker?Да, PM2 предоставляет команду pm2-runtime — готовую замену команде node, предназначенную для запуска приложений на Node.js в защищённом контейнерном окружении для продакшена.
Что означает перезагрузка без простоя в PM2?В режиме кластера PM2 может горячо перезагрузить обновлённое приложение, перезапуская его рабочие процессы по одному, поэтому приложение продолжает обрабатывать запросы без каких-либо простоев.
What are similar projects?forever, nexe, spug, nodemon, webhook, deployer, shelljs, lsoff
Creator
Unitech
Size
14.1 MB
Stars
43.3K
Age
13y
Commits · 90 Days