Cli

Создание приложения Node.js

В качестве примера можно создать простое приложение Hello World; оно будет возвращать фразу Hello World на любой запрос HTTP. Такое приложение можно в дальнейшем использовать в качестве шаблона для более сложного приложения.

Примечание: Копируя код, не забудьте указать свой IP-адрес и порт вместо условных данных.

Код приложения Hello World

Создайте приложение Node.js и откройте его в текстовом редакторе (в руководстве файл называется hello.js):

Вставьте в файл следующий код. При необходимости можно заменить номер порта 8080 (он должен быть от 1024 и больше).

Сохраните и закройте файл.

Данное приложение будет слушать указанный адрес (localhost) и порт (8080) и возвращать фразу Hello World с HTTP-кодом 200. При прослушивании localhost удалённые клиенты не смогут получить доступ к приложению.

Тестирование приложения

Чтобы протестировать приложение, создайте исполняемый файл hello.js:

Запустите его:

Примечание: Запуская Node.js таким образом, вы блокируете дополнительные команды. Они будут доступны после остановки приложения (Ctrl-C).

Чтобы протестировать приложение, откройте новый терминал и подключитесь к localhost с помощью curl:

Если на экране появился следующий вывод, приложение работает правильно:

Если такой вывод не появился, убедитесь, что приложение Node.js запущено и правильно настроено (слушает правильный адрес и порт).

Остановите приложение, нажав Ctrl+C.

Установка PM2

Теперь нужно установить PM2. Это менеджер процессов Node.js. PM2 предоставляет простой способ управления и демонизации приложений.

Установку можно выполнить при помощи пакетного менеджера npm.

При помощи опции –g менеджер npm выполнит глобальную установку PM2.

Troubleshooting

SSH clone errors

In most cases, these errors will be caused by not having the correct keys to clone your repository. You need to verify at every step that the keys are available.

Step 1
If you are certain your keys are correctly working, first try running on the target server. If it succeeds, move onto the next steps. If it failed, make sure your keys are stored both on the server and on your git account.

Step 2
By default copies the default identiy, usually named . If that is not the appropriate key:

This adds your public key to the file.

Step 3
If you get the following error:

…you may want to create a ssh config file. This is a sure way to ensure that the correct ssh keys are used for any given repository you’re trying to clone. See this example:

Considerations

  • You can use the option to skip local change detection
  • You might want to commit your node_modules folder (#622) or add the command to the section:
  • Verify that your remote server has the permission to git clone the repository
  • You can declare specific environment variables depending on the environment you want to deploy the code to. For instance to declare variables for the production environment, add “env_production”: {} and declare the variables.
  • By default, PM2 will use . So you can skip the options if this is the case
  • You can embed the “apps” & “deploy” section in the package.json
  • It deploys your code via ssh, you don’t need any dependencies
  • Processes are initialized / started automatically depending on the application name in
  • PM2-deploy repository can be found here: pm2-deploy
  • WINDOWS : see point below (at the end)

Why?

I advised before reading about the process manager, you must read Part-I about clustering module in NodeJs to know the purpose of process managers.

Process manager will take responsibility for managing applications on different processor cores without being worrying about a master and worker headache. It helps to keep application independent of cores and processes management.

Pros:

  1. Abating code complexity of cores management.
  2. Session management.
  3. Multiple applications management on a server.
  4. Cores utilization responsibility delegated to process manager.
  5. Inter-Process Communication IPC complexity removed.

Which?

There are many process managers available but in the current article, we will explore PM2. Since it is simple, easy and provides features like logging, monitoring, and much more. Later we will compare the performance of PM2 with clustering module for same lines of code as used in the previous example.

To Start:

The following command will start an application. As of now consider that we have applications defined in a script for PM2. Script file example is shared after commands introductions. In case if you are intolerant to jump to an example then directly start reading script example.

pm2 start file-name.js

Restart will kill and start an application

pm2 restart pid or App-name

As opposed to , which kills and restarts the process, achieves a 0-second-downtime reload.

pm2 reload pid or App-name

“All” attribute will affect every process and application.

pm2 reload all

To View Logs:

pm2 logs

Above mentioned commands can be used directly in CLI to start an application but preferred approach is to set up an ecosystem file and control applications from a script file.

Eco System File:

I am using same code base as used in the previous article so a performance comparison can be developed with PM2 and node “Clustering” Module.

I created two applications with the same code base but listening requests on different ports in code while setting up the server by express. Following script will be used for managing these applications from PM2 using ecosystem file.

Script Dissection:

  1. “apps” attribute is used for defining multiple applications on the server. Two apps are defined with their entry point file path is defined in script attribute.
  2. “exec_mode” defines application running mode. It can have two types either “fork” or “cluster” mode. Fork mode is helpful when utilizing pm2 for PHP and python. Cluster mode is defined for node applications which will eventually access NodeJs cluster module on a lower level. It is great for zero-configuration based process management.
  3. “instances” as obvious from the name, PM2 will take care of forking process on multiple instances but listening on the same port. “Clustering” application is defining the maximum number of possible CPU’s available while “Clustering_Replica” application is asking for only two instances.
  4. PM2 also helps to manage application scripts in different environments. Other attributes for staging and production are only added to give a quick idea.

Terminal Output:

Running above script produces the following result showing processes ids along with further relevant information including memory and CPU usage.

Performance Metrics — Clustering vs PM2:

Apache benchmark is used for measuring an application performance, helpful in load testing. Example tested using two approaches, setting up a server with “cluster” module and second with “PM2”. Results were almost the same, a marginal difference which is negligible. Look out the statistics:

Request time in milliseconds

Conclusion:

  1. PM2 is as good as using the cluster module in an application, therefore it is better to use process manager to reduce code complexity.
  2. Multiple applications management is also possible through centralized ecosystem file.
  3. The PM2 dashboard helps in runtime application monitoring.

Release notes

  • Uses 2.x version of pm2-interface, even though it breaks monitoring multiple hosts
  • Shows an error message when attempting to monitor an old/incompatible version of pm2
  • Allow reloading of processes as well as restarting
  • Debug button added to use node-inspector to debug running processes
  • Batch UI updates together in an attempt to improve performance
  • Supports http basic auth
  • Supports serving over HTTPS
  • Serve websockets and UI from a single port to make proxying easier

Introduced external configuration file

Swapped d3/xCharts for HighCharts due to a memory leak

  • Display logs from processes emitted after pm2-web was started
  • Caches logging output between browser refreshes
  • Respects ANSI colour in logging output

Must have been something interesting here

Displays graphs of memory and cpu output

  • Initial release
  • Process listing
  • Restarting, stopping & starting processes

pm2 Flags

Flag name Description
-V, –version output the version number
-v –version get version
-s –silent hide all messages
-m –mini-list display a compacted list without formatting
-f –force force actions
–disable-logs do not write logs
-n –name <name> set a <name> for script
-i –instances <number> launch instances (for networked app)(load balanced)
–parallel <number> number of parallel actions (for restart/reload)
-l –log specify entire log file (error and out are both included)
-o –output <path> specify out log file
-e –error <path> specify error log file
-p –pid <pid> specify pid file
-k –kill-timeout <delay> delay before sending final SIGKILL signal to process
–listen-timeout <delay> listen timeout on application reload
–max-memory-restart <memory> specify max memory amount used to autorestart (in octet or use syntax like 100M)
–restart-delay <delay> specify a delay between restarts (in milliseconds)
–env <environment_name> specify environment to get specific env variables (for JSON declaration)
–log-type <type> specify log output style (raw by default, json optional)
-x –execute-command execute a program using fork system
–max-restarts only restart the script COUNT times
-u –user <username> define user when generating startup script
–uid <uid> run target script with <uid> rights
–gid <gid> run target script with <gid> rights
–cwd <path> run target script as <username>
–hp <home path> define home path when generating startup script
–wait-ip override systemd script to wait for full internet connectivity to launch pm2
–service-name <name> define service name when generating startup script
-c –cron <cron_pattern> restart a running process based on a cron pattern
-w –write write configuration in local folder
–interpreter <interpreter> the interpreter pm2 should use for executing app (bash, python…)
–interpreter-args <arguments> interpret options (alias of –node-args)
–log-date-format <date format> add custom prefix timestamp to logs
–no-daemon run pm2 daemon in the foreground if it doesn’t exist already
-a –update-env update environment on restart/reload (-a <=> apply)
–source-map-support force source map support
–only <application-name> with json declaration, allow to only act on one application
–disable-source-map-support force source map support
–wait-ready ask pm2 to wait for ready event from your app
–merge-logs merge logs from different instances but keep error and out separated
–watch watch application folder for changes (default: )
–ignore-watch <folders|files> folder/files to be ignored watching, should be a specific name or regex — e.g. –ignore-watch=”test node_modules “some scripts””
–node-args <node_args> space delimited arguments to pass to node in cluster mode — e.g. –node-args=”–debug=7001 –trace-deprecation”
–no-color skip colors
–no-vizion start an app without vizion feature (versioning control)
–no-autorestart start an app without automatic restart
–no-treekill Only kill the main process, not detached children
–no-pmx start an app without apm
–no-automation start an app without apm
–trace enable transaction tracing with km
–disable-trace disable transaction tracing with km
–attach attach logging after your start/restart/stop/reload
–sort <field_name:sort> sort process according to field’s name
–v8 enable v8 data collecting
–event-loop-inspector enable event-loop-inspector dump in apm
–deep-monitoring enable all monitoring tools (equivalent to –v8 –event-loop-inspector –trace)
-h, –help output usage information

Создание пользователя

Часто аккаунт root используется для постоянной работы из-за расширенных привилегий. Однако такой подход небезопасен, а ошибка может повлечь за собой массу неприятных последствий. Например, взломав root, злоумышленник может получить полный контроль над сервером.

Для постоянной работы рекомендуется создать другого пользователя. В данном руководстве такой пользователь будет условно называться safeuser (так как он безопаснее, чем root); выберите любое другое удобное имя.

Войдите на сервер как root и создайте нового пользователя с каталогом /home/safeuser/:

Выберите пароль дл этого пользователя.

Откройте пользователю доступ к sudo:

После этого закройте сессию root и откройте сессию нового пользователя.

Управление приложением с помощью PM2

Менеджер процессов PM2 очень прост в использовании. Рассмотрим основы его работы.

Запуск приложения

Для запуска приложений в фоновом режиме используется команда pm2 start:

Также эта команда добавит приложение в список процессов PM2, который выводится на экран при запуске каждого приложения:

Как видите, PM2 автоматически устанавливает App name (имя файла без расширения .js) и PM2 id. Также PM2 предоставляет другую информацию: PID процесса, текущее состояние, использование памяти.

Запущенное с помощью PM2 приложение будет автоматически перезапускаться в случае ошибок или сбоев, однако автоматический запуск приложения нужно настроить отдельно. Для этого существует подкоманда startup.

Эта команда генерирует и настраивает сценарий запуска менеджера PM2 и всех его процессов вместе с загрузкой сервера. Также нужно указать платформу (в данном случае это ubuntu).

В последней строке вывода находится команда, которую нужно запустить с привилегиями суперпользователя:

Запустите сгенерированную команду, чтобы настроить автозапуск PM2.

Эта команда создаст unit-файл для systemd, запускающий pm2 при запуске сервера. Менеджер pm2, в свою очередь, запустит приложение hello.js. Проверьте состояние юнита systemd:

Другие функции PM2 (опционально)

PM2 предоставляет множество других функций, которые позволяют управлять или просматривать информацию о приложениях

Обратите внимание, что запуск PM2 без каких-либо аргументов отобразит страницу справкина которой можно найти подробные примеры использования PM2

Остановить приложение можно при помощи:

Чтобы перезапустить приложение, введите:

Список приложений, управляемых PM2, можно просмотреть при помощи следующей подкоманды:

Подробную информацию о конкретном приложении можно получить с помощью подкоманды info:

Подкоманда monit показывает данные процесса PM2: состояние приложения, использование CPU и памяти:

Теперь нужно настроить обратный прокси.

Use PM2 inside Containers

In your Dockerfile add this line to install PM2:

Then replace the binary with

to:

You are now all set! Your Node.js application is now wrapped into a proper Node.js production environment.

Starting a configuration file

Instead of running your raw Node.js application with PM2, you can declare it into a configuration file (or process file) and set some configuration variables, like enabling the cluster mode.

Let’s create a ecosystem.config.js file with this content:

All options available are .

You can then replace the CMD directive by this:

To split each processes in his own Docker, you can use the –only option:

Logging Format option

If you want to change the log output format you can select one of this options:

  • –json: will output logs in JSON format (logstash)
  • –format: will output logs in = style format
  • –raw: will output logs as is

To use one of this flag, you just need to pass them to pm2-runtime:

Enabling Graceful Shutdown

When the Container receives a shutdown signal, PM2 forwards this signal to your application allowing to close all the database connections, wait that all queries have been processed or that any other final processing has been completed before a successfull graceful shutdown.

Catching a shutdown signal is straightforward. You need to add a listener in your Node.js applications and execute anything needed before stopping the app:

By default PM2 will wait 1600ms before sending a final SIGKILL signal. You can modify this delay by setting the option inside your application configuration file.

Read more about application state management here

Development environment

You may want to tell Developers to program inside a container to keep a consistant environment between develoment, test and production.

Replacing pm2-runtime with pm2-dev will enable the watch and restart features. This is quite interesting in a development container when the host files are exposed to the container as a VOLUME.

Using PM2.io

Keymetrics.io is a monitoring service built on top of PM2 that allows to monitor and manage applications easily (logs, restart, exceptions monitoring…). Once you created a Bucket on Keymetrics you will get a public and a secret key.

To enable Keymetrics monitoring with pm2-runtime, you can either use the CLI option –public XXX and –secret YYY or pass the environment variables KEYMETRICS_PUBLIC and KEYMETRICS_SECRET.

Example with the CLI options via a Dockerfile:

Or via environment variables:

Or via the Docker run command:

Metrics monitoring

can monitor any PMX metrics defined in your apps.

To configure rules of alerting, setup section in module config file.

"metric"{"metric name"{"target","op"">","ifChanged"true,"noNotify"true,"noHistory"true,"exclude"false},"metric 2"{...}}
  • — name of metric defined in one of your apps

  • — target numeric value

  • — operator to compare metric value and target. Can be one of: , , , , ,

  • — if , alert will trigger only if current metric value is different from last recorded value (optional)

  • — if , no alerts will be send (optional)

  • — if , metric value history won’t be stored (optional)

  • — if , metric will be complettely excluded from monitoring (optional)

  • — if , metric value won’t be converted to number (optional)

By default, and metrics are added.

Запуск приложения при помощи PM2

Запуск приложения через PM2 имеет некоторые преимущества. Для этого введите команду:

На экране появится отчёт:

App Name id mode PID status port Restarted Uptime memory err logs
app cluster 22654 online 0s 8.035 MB /home/safeuser/.pm/app-err.log

Любое приложение, запущенное при помощи менеджера процессов PM2, будет автоматически перезапущено в случае сбоя; также оно будет работать как сервис. Кроме того, PM2 ведёт лог необработанных исключений (в данном случае /home/safeuser/.pm/app-err.log).

Чтобы запустить приложение как сервис, введите:

Примечание: Замените safeuser именем своего пользователя.

На экране появится вывод:

Теперь приложение запущено при помощи не-root пользователя на порт 80. Также оно будет автоматически перезапущено в случае сбоя и во время загрузки сервера. Это очень надёжная среда для запуска приложения в производство.

Generate configuration

To generate a sample process file you can type this command:

This will generate a sample :

Once edited at your convenience you can start/restart/stop/delete this file via CLI:

Checkout on ecosystem.config.js to know more.

Javascript format

You can declare multiple application easily and specify different options for each of them:

Note that using a Javascript configuration file requires to end the file name with

You can also act on a particular application by using its name and the option :

For multiple processes use:

Switching environments

You may have noticed that you can declare environment-specific variables with the attribute (e.g. env_production, env_staging…). They can be switched easily. You just need to specify the when acting on the application declaration.

Example:

Configuration

After installation run to configure module. Alternatively edit file directly (in PM2 home folder).

"pm2-health"{"smtp"{"host""your-smtp-host","port"587,"from""your-from-mail",ifnotset,userwillbeused"user""your-smtp-user",auth"password""your-smtp-password",auth"secure"false,"disabled"false},"mailTo""mail1,mail2"}
  • — SMTP server configuration. If your SMTP doesn’t require auth, leave empty

  • — comma separated list of notification receipients

  • — reply to address (optional)

  • — list of events to monitor (optional). If not set, all events will be monitored.

  • — if apps exceptions will be monitored (optional)

  • — how often PMX metrics will be tested in seconds (optional). If not set, 60 seconds is used

  • — if app logs will be added as mail attachement (optional)

  • — array of app names to exclude from monitoring (optional)

  • — array of app names to include, if set is ignored (optional)

  • — if debug log is enabled, by default is (optional)

Custom messages

On top of standard PM2 events, you can monitor custom messages sent from your apps.

To send message from your app use:

process.send({    type"process:msg",    data{...}});
  • — must be

  • — object containing additional data (optional).

You can exclude some of the messages based on their content:

  1. Add regular expression to list in config property
  2. (converted to JSON string) will be tested with this all expressions in the list
  3. If any test is positive, message will be excluded

Example:

You wish to monitor slow operations in your app, so you send custom messages like so:

functionslow(operation,duration){process.send({ type"process:msg", data{ operation, duration }});}

You know that and operations are always slow and wish to exclude them, but still get other slow operations.

Set config to:

"messageExcludeExps""\"operation\"\"(backup|restore)\""

Детектирование изменений¶

В pm2 также можно настроить автоматический перезапуск приложения при изменении одного из его файлов. Для этого при старте приложения укажите параметр .

Процесс отслеживания изменений не завершается с остановкой процесса приложения. Чтобы отключить его, при выполнении команды также необходимо передать параметр .

Параметр имеет ряд параметров, но их указание возможно только через файл .

ecosystem.config.js

Здесь в параметре явно указывается, изменений каких директорий необходимо отслеживать. Чтобы исключить из отслеживания определенные директории, имеется параметр . А с помощью указывается время в миллисекундах, которое необходимо выждать при перезапуске приложения, прежде чем инициировать процесс детектирования изменений.

pm2 Commands

Command name Description
start <file|json|stdin|app_name|pm_id…> start and daemonize an app
trigger <proc_name> <action_name> deploy your json
deploy <file|environment> deploy your json
startOrRestart <json> start or restart JSON file
startOrReload <json> start or gracefully reload JSON file
pid return pid of or all
startOrGracefulReload <json> start or gracefully reload JSON file
stop <id|name|all|json|stdin…> stop a process (to start it again, do pm2 restart <app>)
restart <id|name|all|json|stdin…> restart a process
scale <app_name> <number> scale up/down a process in cluster mode depending on total_number param
snapshot snapshot PM2 memory
profile <command> profile CPU
reload <name|all> reload processes (note that its for app using HTTP/HTTPS)
gracefulReload <name|all> gracefully reload a process. Send a “shutdown” message to close all connections.
id <name> get process id by name
delete <name|id|script|all|json|stdin…> stop and delete a process from pm2 process list
sendSignal <signal> <pm2_id|name> send a system signal to the target process
ping ping pm2 daemon — if not up it will launch it
updatePM2 update in-memory PM2 with local PM2
update (alias) update in-memory PM2 with local PM2
install|module:install install or update a module (or a set of modules) and run it forever
module:update <module|git:/> update a module and run it forever
module:generate Generate a sample module in current folder
uninstall|module:uninstall <module> stop and uninstall a module
publish|module:publish Publish the module you are currently on
set sets the specified config <key> <value>
multiset <value> multiset eg “key1 val1 key2 val2
get get value for <key>
conf get / set module config values
config <key> get / set module config values
unset <key> clears the specified config <key>
report give a full pm2 report for https://github.com/Unitech/pm2/issues
link|interact linking action to keymetrics.io — command can be stop|info|delete|restart
unlink linking action to keymetrics.io — command can be stop|info|delete|restart
unmonitor unmonitor target process
monitor monitor target process
open open dashboard in browser
register create an account on keymetrics
login login to keymetrics and link current PM2
web launch a health API on 0.0.0.0:9615
dump|save dump all processes for resurrecting them later
send <pm_id> <line> send stdin to <pm_id>
attach <pm_id> attach stdin/stdout to application identified by <pm_id>
resurrect resurrect previously dumped processes
unstartup disable and clear auto startup — =systemd,upstart,launchd,rcd
startup setup script for pm2 at boot — =systemd,upstart,launchd,rcd
logrotate copy default logrotate configuration
ecosystem|init generate a process conf file. (mode = null or simple)
reset <name|id|all> reset counters for process
describe <id> describe all parameters of a process id
desc <id> (alias) describe all parameters of a process id
info <id> (alias) describe all parameters of a process id
show <id> (alias) describe all parameters of a process id
list|ls list all processes
l (alias) list all processes
ps (alias) list all processes
status (alias) list all processes
jlist list all processes in JSON format
prettylist print json in a prettified JSON
monit launch termcaps monitoring
imonit launch legacy termcaps monitoring
dashboard|dash launch dashboard with monitoring and logs
flush flush logs
reloadLogs reload all logs
logs stream logs file. Default stream all logs
kill kill daemon
pull <name> updates repository for a given app
forward <name> updates repository to the next commit for a given app
backward <name> downgrades repository to the previous commit for a given app
gc force PM2 to trigger garbage collection
deepUpdate performs a deep update of PM2
serve|expose serve a directory over http via port

Considerations

All command line options passed when using the JSON app declaration will be dropped i.e.

You can start as many JSON application declarations as you want.

Will result in two apps launched:

CWD

cwd: your JSON declaration does not need to reside with your script. If you wish to maintain the JSON(s) in a location other than your script (say, ) you will need to use the feature (Note, this can be really helpful for capistrano style directory structures that uses symlinks). Files can be either relative to the directory, or absolute (see example below).

CLI/JSON options

All the keys can be used in a JSON configured file, but will remain almost the same on the command line e.g.:

Using quotes to make an ESC, e.g.:

The argument will be parsed as

but not

Disabling logs

You can pass to error_file or out_file to disable logs saving.
Note: starting PM2 , or disable logs independently of the platform.

Environment definition

You’ll need to use to tell pm2 to use specific environment defined inside a process file :

In this example, you will run and it will start your application with the default environment (in development so).
Then you use and it will use the attribute where name is here, so it will start your app with .

Special

  • min_uptime
    Value of can be:

    • Number
      e.g. means 3000 milliseconds.
    • String
      Therefore, we are making it short and easy to configure: , and , e.g.: means one hour, means five minutes and means ten seconds (those will be transformed into milliseconds).
  • max_memory_restart
    Value of can be:

    • Number
      e.g. means 1024 bytes (NOT BITS).
    • String
      Therefore, we are making it short and easy to configure: , and , e.g.: means one gigabyte, means five megabytes and means ten kilobytes (those will be transformed into byte(s)).
  • Optional values
    For example can take () or () as possible values.

  • Things to know
    • means that PM2 will launch the maximum processes possible according to the numbers of CPUs (cluster mode)
    • array
      , and could be type of (e.g.: ) or (e.g.: )

Contribute to this page

Reload/restart processes

Restarting a process stops the current process and starts a new one, dropping connections in the process.

Reloading starts a new process in the background, killing the old process after the new one has initialised which reduces downtime.

N.b. your process must exit cleanly (e.g. close sockets, database connections) otherwise the old process will never be killed.

Soft reloading (the default) will cause pm2 to send your process a message and kill it shortly afterwards. Hard reloading will kill it immediately.

To control this behaviour, specify the following in your config file:

{"forceHardReload"false}

To listen for the event, add the following to your program:

process.on("message",function(message){if(message =="shutdown"){}});

You can tweak the resource usage graph to be more or less specific. The thinking here is that lots of processes with lots of process usage data will make your browser a bit crashey.

By default it will retain 1000 resource usage measurements of a process (CPU and memory) over a maximum of five days with 40% of the measurements taken in the last 24 hours, 25% from the day before, 10% each from the two days before that and 5% from the day before that.

The update frequency of the graph is controlled by as detailed above.

The number of data points that will be plotted on the graph in total. If you’ve got a lot of processes, you may wish to set this to a lowish number to minimise memory consumption in your browser and the pm2-web process itself.

The number of arguments is the number of days worth of data to graph (default 5) and the value is what percentage of should be plotted on a given day (the first argument is today, the second is yesterday, etc).

What this means is that any recent resource usage data will have a more accurate representation in the graph at the cost of consuming more memory and older data will be less accurate but also less likely to crash your browser.

pm2-web will display log lines emitted by monitored processes after pm2-web itself was started. In order to keep resource usage reasonable by default it will show 1000 log lines.

You can alter this behaviour by specifying , so for example to lower this to 500 lines:

Docker Integration

Using Containers? We got your back. Start today using pm2-runtime, a perfect companion to get the most out of Node.js in production environment.

The goal of pm2-runtime is to wrap your applications into a proper Node.js production environment. It solves major issues when running Node.js applications inside a container like:

  • Second Process Fallback for High Application Reliability
  • Process Flow Control
  • Automatic Application Monitoring to keep it always sane and high performing
  • Automatic Source Map Discovery and Resolving Support

Further than that, using PM2 as a layer between the container and the application brings PM2 powerful features like application declaration file, customizable log system and other great features to manage your Node.js application in production environment.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *