### Install PM2 and Start Application Programmatically Source: https://github.com/unitech/pm2/wiki/Home Install PM2 using npm and use its programmatic API to start an application with cluster mode, multiple instances, and memory restart configuration. ```bash $ npm install pm2 --save ``` ```javascript var pm2 = require('pm2'); pm2.connect(function(err) { if (err) { console.error(err); process.exit(2); } pm2.start({ script : 'app.js', // Script to be run exec_mode : 'cluster', // Allow your app to be clustered instances : 4, // Optional: Scale your app by 4 max_memory_restart : '100M' // Optional: Restart your app if it reaches 100Mo }, function(err, apps) { pm2.disconnect(); }); }); ``` -------------------------------- ### Clone and Setup PM2 Development Environment Source: https://github.com/unitech/pm2/blob/master/CONTRIBUTING.md Clone the PM2 repository, switch to the development branch, and install dependencies to set up a local development environment. ```bash $ git clone https://github.com/Unitech/pm2.git $ cd pm2 $ git checkout development $ npm install ``` -------------------------------- ### Cluster Mode Instance Options Source: https://github.com/unitech/pm2/wiki/Home Examples of starting an application in cluster mode with different instance counts, including maximum available CPUs and a specific number of processes. ```bash $ pm2 start app.js -i 1 ``` ```bash $ pm2 start app.js -i 0 ``` ```bash $ pm2 start app.js -i -1 ``` ```bash $ pm2 start app.js -i 3 ``` -------------------------------- ### Install and Start CoffeeScript App with PM2 Source: https://github.com/unitech/pm2/blob/master/examples/using-pm2-and-transpilers/README.md Install the CoffeeScript module for PM2 and then start an echo application written in CoffeeScript. ```bash $ pm2 install coffee-script $ pm2 start echo.coffee ``` -------------------------------- ### Install and Start TypeScript App with PM2 Source: https://github.com/unitech/pm2/blob/master/examples/using-pm2-and-transpilers/README.md Install the TypeScript module for PM2 and then start an HTTP server application written in TypeScript. ```bash $ pm2 install typescript $ pm2 start http.ts ``` -------------------------------- ### Install and Start LiveScript App with PM2 Source: https://github.com/unitech/pm2/blob/master/examples/using-pm2-and-transpilers/README.md Install the LiveScript module for PM2 and then start an echo application written in LiveScript. ```bash $ pm2 install livescript $ pm2 start echo.ls ``` -------------------------------- ### Start App from Configuration File (CLI) Source: https://github.com/unitech/pm2/wiki/Cluster-Mode Use the `pm2 start` command with a JSON configuration file to launch your application with the specified settings. ```bash $ pm2 start processes.json ``` -------------------------------- ### Start Application with PM2 CLI Source: https://github.com/unitech/pm2/wiki/Home Use `pm2 start` to launch an application. You can specify a name for easier management. ```bash $ pm2 start app.js --name "my-api" $ pm2 start web.js --name "web-interface" ``` -------------------------------- ### Starting Multiple JSON App Declarations Source: https://github.com/unitech/pm2/wiki/Home Demonstrates how to start multiple applications using separate JSON declaration files and how to view running processes. ```bash $ pm2 start node-app-2.json $ ps aux | grep node-app ``` -------------------------------- ### Example PM2 Startup Command Source: https://github.com/unitech/pm2/wiki/Start-PM2-at-Startup An example of the command PM2 might output, which needs to be executed as root. It includes environment variables and user/home path configuration. ```bash [PM2] You have to run this command as root. Execute the following command: sudo su -c "env PATH=$PATH:/home/unitech/.nvm/versions/node/v4.3/bin pm2 startup -u --hp ``` -------------------------------- ### Install PM2 using APT Source: https://github.com/unitech/pm2/wiki/Installing-PM2-with-APT Follow these commands to add the PM2 repository and install PM2 on your Ubuntu system. ```bash # 1. Add the PM2 repository signing key sudo apt-key adv --keyserver keyserver.ubuntu.com --recv D1EA2D4C ``` ```bash # 2. Add the PM2 repository echo "deb http://apt.pm2.io/ubuntu stable main" | sudo tee /etc/apt/sources.list.d/pm2.list ``` ```bash # 3. Update list of available packages sudo apt-get update ``` ```bash # 4. Install PM2 sudo apt-get install pm2 ``` -------------------------------- ### Start Application with PM2 Configuration Source: https://github.com/unitech/pm2/blob/master/examples/expose-custom-metrics/README.md Use this command to start your application using a PM2 configuration file, which is necessary for exposing custom metrics. ```bash $ pm2 start process.config.js ``` -------------------------------- ### Start Applications with PM2 Source: https://github.com/unitech/pm2/blob/master/pres/TMP.md Start, daemonize, and auto-restart applications. Supports Node.js, Python, and bash scripts. Can also start applications defined in a JSON configuration file. ```bash $ pm2 start app.js # Start, Daemonize and auto-restart application (Node) ``` ```bash $ pm2 start app.py # Start, Daemonize and auto-restart application (Python) ``` ```bash $ pm2 start npm -- start # Start, Daemonize and auto-restart Node application ``` ```bash $ pm2 start script.sh # Start bash script ``` ```bash $ pm2 start app.json # Start all applications declared in app.json ``` -------------------------------- ### Start Application Without Daemonizing Source: https://github.com/unitech/pm2/wiki/Home Starts an application in the foreground without daemonizing it. ```bash $ pm2 start app.js --no-daemon ``` -------------------------------- ### Start Node.js Applications with PM2 Source: https://github.com/unitech/pm2/wiki/Home Basic commands to start Node.js applications. Use `-- -a 23` to pass arguments to your script, `--name` to assign a specific name for easier management, `--node-args` to pass options to the V8 engine, `-i 0` for cluster mode with maximum instances, `--log-date-format` for custom log prefixes, or `app.json` to start processes defined in a configuration file. You can also specify output and error log files with `-e` and `-o`. ```bash $ pm2 start app.js # Start app.js $ pm2 start app.js -- -a 23 # Pass arguments '-a 23' argument to app.js script $ pm2 start app.js --name serverone # Start a process an name it as server one # you can now stop the process by doing # pm2 stop serverone $ pm2 start app.js --node-args="--debug=7001" # --node-args to pass options to node V8 $ pm2 start app.js -i 0 # Start maximum processes depending on available CPUs (cluster mode) $ pm2 start app.js --log-date-format "YYYY-MM-DD HH:mm Z" # Log will be prefixed with custom time format $ pm2 start app.json # Start processes with options declared in app.json # Go to chapter Multi process JSON declaration for more $ pm2 start app.js -e err.log -o out.log # Start and specify error and out log ``` -------------------------------- ### Install PM2 using Bun Source: https://github.com/unitech/pm2/blob/master/README.md Install PM2 globally on your system using the Bun package manager. ```bash $ bun install pm2 -g ``` -------------------------------- ### Start App in Cluster Mode (CLI) Source: https://github.com/unitech/pm2/wiki/Cluster-Mode Use the `pm2 start` command with the `-i max` option to scale your application across all available CPU cores. ```bash $ pm2 start app.js -i max ``` -------------------------------- ### Starting Multiple JSON Applications with PM2 Source: https://github.com/unitech/pm2/wiki/Applications-Declaration Demonstrates how to start multiple applications using separate JSON declaration files with the PM2 CLI. Shows the expected output of `ps aux` to verify running applications. ```bash $ cat node-app-1.json { "name" : "node-app-1", "script" : "app.js", "cwd" : "/srv/node-app-1/current" } ``` ```bash $ pm2 start node-app-2.json $ ps aux | grep node-app root 14735 5.8 1.1 752476 83932 ? Sl 00:08 0:00 pm2: node-app-1 root 24271 0.0 0.3 696428 24208 ? Sl 17:36 0:00 pm2: node-app-2 ``` -------------------------------- ### Start an Application with PM2 Source: https://github.com/unitech/pm2/blob/master/README.md Use this command to start any application (Node.js, Bun, Python, Ruby, binaries) and have it daemonized, monitored, and kept alive forever. ```bash $ pm2 start app.js ``` -------------------------------- ### Initialize PM2 Module Entry Point Source: https://github.com/unitech/pm2/wiki/Modules Example of the main module entry point, initializing the module with pmx.initModule and handling potential errors. ```javascript var pmx = require('pmx'); var conf = pmx.initModule({ // Override PID to be monitored pid : pmx.resolvePidPaths(['/var/run/redis.pid']), }, function(err, conf) { // Now the module is initialized require('./business_logic.js')(conf); }); ``` -------------------------------- ### Start PM2 with a Configuration File Source: https://github.com/unitech/pm2/wiki/Docker-Integration Instructs `pm2-docker` to start applications defined in a `process.yml` configuration file. This allows for more complex application management. ```dockerfile CMD ["pm2-docker", "process.yml"] ``` -------------------------------- ### Start Applications with JSON Ecosystem File Source: https://github.com/unitech/pm2/blob/master/examples/ecosystem-file/README.md Initiate applications using a JSON ecosystem file. Verify the 'process.json' file structure and content before execution. ```bash $ pm2 start process.json ``` -------------------------------- ### Generate and Install a PM2 Module Source: https://github.com/unitech/pm2/wiki/Modules Steps to generate a new module boilerplate, install it locally, and notes on automatic restarts. ```bash $ pm2 module:generate $ cd $ pm2 install . ``` ```bash # To display module logs: $ pm2 logs # To remove the module: $ pm2 uninstall ``` -------------------------------- ### Start HTTP App in Cluster Mode Source: https://github.com/unitech/pm2/blob/master/examples/cluster-http/README.md Use this command to start your HTTP application in cluster mode. You can either specify a configuration file or start directly with the `-i max` flag to utilize all available CPU cores. ```bash $ pm2 start ecosystem.config.js ``` ```bash # OR $ pm2 start http.js -i max ``` -------------------------------- ### Install Build Dependencies on Ubuntu Source: https://github.com/unitech/pm2/wiki/Home Install essential build tools and Node.js version manager (nvm) for testing PM2 on Ubuntu. ```bash $ sudo apt-get install build-essential # nvm is a Node.js version manager - https://github.com/creationix/nvm $ wget -qO- https://raw.github.com/creationix/nvm/master/install.sh | sh $ nvm install v0.11.14 $ nvm use v0.11.14 $ nvm alias default v0.11.14 ``` -------------------------------- ### Install pm2-logrotate Module Source: https://github.com/unitech/pm2/wiki/Log-Management Install the pm2-logrotate module for automatic log rotation. This is an external module. ```bash $ pm2 install pm2-logrotate ``` -------------------------------- ### Install and Manage a PM2 Module Source: https://github.com/unitech/pm2/blob/master/examples/module-test/README.md Commands to install, view logs, uninstall, and restart a PM2 module after it has been generated. ```bash Start module in development mode: $ cd module-test/ $ pm2 install . Module Log: $ pm2 logs module-test Uninstall module: $ pm2 uninstall module-test Force restart: $ pm2 restart module-test ``` -------------------------------- ### Start Applications in Cluster Mode Source: https://github.com/unitech/pm2/wiki/Home Starts an application in cluster mode, utilizing multiple CPU cores to handle more traffic. '-i 0' starts the maximum number of processes based on available CPUs. ```bash $ pm2 start app.js -i 0 ``` -------------------------------- ### Install PM2 Development Version Source: https://github.com/unitech/pm2/wiki/Home Install the development branch of PM2 globally using npm. ```bash $ npm install git://github.com/Unitech/pm2#development -g ``` -------------------------------- ### Start and Manage Application Processes Source: https://github.com/unitech/pm2/wiki/Process-Management Use these commands to start, stop, restart, and delete applications managed by PM2. The `name` flag is used for easy identification. ```bash $ pm2 start app.js --name "my-api" $ pm2 start web.js --name "web-interface" ``` ```bash $ pm2 stop web-interface ``` ```bash $ pm2 restart web-interface ``` ```bash $ pm2 delete web-interface ``` -------------------------------- ### Start Applications with YAML Ecosystem File Source: https://github.com/unitech/pm2/blob/master/examples/ecosystem-file/README.md Launch applications defined in a YAML ecosystem file. Ensure the 'process.yml' file is valid YAML and correctly specifies application configurations. ```bash $ pm2 start process.yml ``` -------------------------------- ### Start Application with Keymetrics Integration Source: https://github.com/unitech/pm2/wiki/Home This snippet demonstrates how to start a Node.js application with PM2 and integrate it with Keymetrics for monitoring. It includes placeholders for Keymetrics keys and machine name, and specifies post-update commands. ```javascript var pm2 = require('pm2'); var MACHINE_NAME = 'hk1'; var PRIVATE_KEY = 'XXXXX'; // Keymetrics Private key var PUBLIC_KEY = 'XXXXX'; // Keymetrics Public key var instances = process.env.WEB_CONCURRENCY || -1; // Set by Heroku or -1 to scale to max cpu core -1 var maxMemory = process.env.WEB_MEMORY || 512;// " " " pm2.connect(function() { pm2.start({ script : 'app.js', name : 'production-app', // ----> THESE ATTRIBUTES ARE OPTIONAL: exec_mode : 'cluster', // ----> https://github.com/Unitech/PM2/blob/master/ADVANCED_README.md#schema instances : instances, max_memory_restart : maxMemory + 'M', // Auto restart if process taking more than XXmo env: { // If needed declare some environment variables "NODE_ENV": "production", "AWESOME_SERVICE_API_TOKEN": "xxx" }, post_update: ["npm install"] // Commands to execute once we do a pull from Keymetrics }, function() { pm2.interact(PRIVATE_KEY, PUBLIC_KEY, MACHINE_NAME, function() { // Display logs in standard output pm2.launchBus(function(err, bus) { console.log('[PM2] Log streaming started'); bus.on('log:out', function(packet) { console.log('[App:%s] %s', packet.process.name, packet.data); }); bus.on('log:err', function(packet) { console.error('[App:%s][Err] %s', packet.process.name, packet.data); }); }); }); }); }); ``` -------------------------------- ### Start Application in Development Mode Source: https://github.com/unitech/pm2/wiki/Home Use `pm2-dev` to start an application and automatically restart it on file changes, printing logs to the console. ```bash $ pm2-dev run my-app.js ``` -------------------------------- ### Start an Application with PM2 Source: https://github.com/unitech/pm2/wiki/Home Use this command to start a Node.js application in production mode. PM2 will monitor and keep the application alive indefinitely. ```bash $ pm2 start app.js ``` ```bash $ pm2 start ./bin/www -n SiteName ``` -------------------------------- ### Install a PM2 Module Source: https://github.com/unitech/pm2/wiki/Home Use this command to install a PM2 compatible module. These modules extend PM2's functionality. ```bash $ pm2 install ``` -------------------------------- ### Run PM2 Tests Source: https://github.com/unitech/pm2/wiki/Home Clone the PM2 repository, install dependencies, and run the test suite. Ensure you have necessary build tools and Node.js versions installed. ```bash $ git clone https://github.com/Unitech/pm2.git $ cd pm2 $ npm install # Or do NODE_ENV=development npm install if some packages are missing $ npm test ``` -------------------------------- ### Start Application with Merged Logs and Custom Date Format (CLI) Source: https://github.com/unitech/pm2/wiki/Log-Management Start an application using the CLI, merging stdout and stderr logs into a single file and prefixing logs with a custom timestamp format. ```bash $ pm2 start echo.js --merge-logs --log-date-format="YYYY-MM-DD HH:mm Z" ``` -------------------------------- ### Install PM2 Development Version Source: https://github.com/unitech/pm2/blob/master/test/README.md Use this command to install the latest development version of PM2 globally from its GitHub repository. ```bash $ npm install git://github.com/Unitech/pm2.git#development -g ``` -------------------------------- ### Start App with Watch Enabled Source: https://github.com/unitech/pm2/wiki/Watch-and-Restart Enable the watch feature when starting an application to automatically restart it on file changes. ```bash $ pm2 start app.js --watch ``` -------------------------------- ### Start HTTP Application in Cluster Mode with PM2 Source: https://github.com/unitech/pm2/blob/master/test/programmatic/fixtures/tar-module/multi-app-module/README.md Use the 'pm2 start' command with an ecosystem configuration file or directly with a script and the '-i max' flag to run your application in cluster mode, utilizing all available CPU cores. ```bash $ pm2 start ecosystem.config.js ``` ```bash $ pm2 start http.js -i max ``` -------------------------------- ### Start an Application Programmatically Source: https://github.com/unitech/pm2/wiki/Home Use `pm2.start` to launch a new application. It accepts a script path, JSON object, or JSON path, along with options and a callback function. ```javascript pm2.start(script_path|json_object|json_path, options, fn(err, proc){}) ``` -------------------------------- ### Install pm2-logrotate Module Source: https://github.com/unitech/pm2/wiki/Home Install the 'pm2-logrotate' module using the PM2 command-line interface. This module automates log rotation for PM2 and applications it manages. ```bash $pm2 install pm2-logrotate ``` -------------------------------- ### SSH Config File Example Source: https://github.com/unitech/pm2/wiki/Deployment Example configuration for an SSH config file to manage host aliases, hostnames, users, and identity files for specific connections. ```sshconfig # ~/.ssh/config Host alias HostName myserver.com User username IdentityFile ~/.ssh/mykey # Usage: `ssh alias` # Alternative: `ssh -i ~/.ssh/mykey username@myserver.com` Host deployment HostName github.com User username IdentityFile ~/.ssh/github_rsa # Usage: ``` -------------------------------- ### Start an App Reading Stdin with PM2 Source: https://github.com/unitech/pm2/blob/master/examples/interact-via-stdin/README.md Use this command to start a Node.js application that reads from stdin. Ensure your application script (e.g., stdin.js) is in the current directory. ```bash $ pm2 start stdin.js ``` -------------------------------- ### Start Specific App from Configuration File Source: https://github.com/unitech/pm2/wiki/Docker-Integration Starts only a specific application defined in `process.yml` using the `--only` flag. Useful for splitting processes into separate Docker containers. ```dockerfile CMD ["pm2-docker", "process.yml", "--only", "APP"] ``` -------------------------------- ### pm2-docker Helper Usage Source: https://github.com/unitech/pm2/wiki/Docker-Integration Displays the help information for the `pm2-docker` command, outlining its available commands and options for starting applications and managing logs. ```bash >>> pm2-docker -h Usage: start Commands: * start [options] start json_file or application Options: -h, --help output usage information -V, --version output the version number --raw raw log output --json output logs in json format --format output logs formated like key=val --secret [key] keymetrics secret key --public [key] keymetrics public key --machine-name [name] keymetrics machine name --auto-exit exit if all processes are errored/stopped or 0 apps launched --watch watch and Restart --env [name] select env_[name] env variables in process config file ``` -------------------------------- ### PM2 Start/Restart Commands Source: https://github.com/unitech/pm2/wiki/Deployment Commands to start, restart, or reload applications based on a JSON configuration file. ```bash $ pm2 startOrRestart all.json # Invoke restart on all apps in JSON ``` ```bash $ pm2 startOrReload all.json # Invoke reload ``` ```bash $ pm2 startOrGracefulReload all.json # Invoke gracefulReload ``` -------------------------------- ### PM2 Module Configuration in package.json Source: https://github.com/unitech/pm2/wiki/Modules Example of a package.json file for a PM2 module, including dependencies, configuration values, and application behavior options. ```json { "name": "pm2-logrotate", // Used as the module name "version": "1.0.0", // Used as the module version "description": "my desc", // Used as the module comment "dependencies": { "pmx": "latest" }, "config": { // Default configuration values // These values can be overriden with `pm2 set : ` "days_interval" : 7, // These value is returned once you call pmx.initModule() "max_size" : 5242880 }, "apps" : [{ "script" : "index.js", "merge_logs" : true, "max_memory_restart" : "200M" }], "author": "Gataca Sanders", "license": "MIT" } ``` -------------------------------- ### Start TCP App in Cluster Mode Source: https://github.com/unitech/pm2/blob/master/examples/cluster-tcp/README.md Use this command to start your TCP application using an ecosystem configuration file. Alternatively, you can specify the script and use the '-i max' flag to automatically scale to the maximum number of CPU cores. ```bash $ pm2 start ecosystem.config.js ``` ```bash # OR $ pm2 start tcp.js -i max ``` -------------------------------- ### Accessing Default Module Configuration Values Source: https://github.com/unitech/pm2/wiki/Modules Example demonstrating how to declare default configuration values in package.json and access them after initializing the module. ```javascript var conf = pmx.initModule({[...]}, function(err, conf) { // Now we can read these values console.log(conf.days_interval); }); ``` -------------------------------- ### Start HTTP Server in Cluster Mode via CLI Source: https://github.com/unitech/pm2/blob/master/lib/templates/sample-apps/http-server/README.md Use this command to start your HTTP/TCP application in cluster mode, scaling it to the maximum number of available CPU cores. ```bash $ pm2 start api.js -i max ``` -------------------------------- ### Start Application in Cluster Mode with PM2 Source: https://github.com/unitech/pm2/blob/master/README.md Leverage all available CPUs for your Node.js application by starting it in cluster mode with PM2. The `` argument can be 'max', -1 (all CPUs minus 1), or a specific number. ```bash $ pm2 start api.js -i ``` -------------------------------- ### Start CoffeeScript with PM2 Source: https://github.com/unitech/pm2/wiki/Home Execute CoffeeScript files using PM2 by specifying `coffee` as the interpreter. This allows direct execution of `.coffee` files. ```bash $ pm2 start server.coffee --interpreter coffee ``` -------------------------------- ### Start Application with Memory Restart Limit (CLI) Source: https://github.com/unitech/pm2/wiki/Application-Monitoring Start an application using the PM2 CLI and specify a maximum memory limit. If the application exceeds this limit, PM2 will attempt to restart it. Note that the check interval is 30 seconds. ```bash $ pm2 start big-array.js --max-memory-restart 20M ``` -------------------------------- ### JSON Application Declaration Example Source: https://github.com/unitech/pm2/wiki/Applications-Declaration Example of a JSON file used to declare and configure a Node.js application for PM2. Specifies the application name, script path, and working directory. ```json { "name" : "node-app-1", "script" : "app.js", "cwd" : "/srv/node-app-1/current" } ``` -------------------------------- ### Module System with PM2 Source: https://github.com/unitech/pm2/blob/master/pres/TMP.md Manage PM2 modules, including generating sample modules, installing, and uninstalling them. Also includes a command to publish modules. ```bash $ pm2 module:generate [name] # Generate sample module with name [name] ``` ```bash $ pm2 install pm2-logrotate # Install module (here a log rotation system) ``` ```bash $ pm2 uninstall pm2-logrotate # Uninstall module ``` ```bash $ pm2 publish # Increment version, git push and npm publish ``` -------------------------------- ### Start App with Watch Mode Source: https://github.com/unitech/pm2/wiki/Home This command starts an application and enables watch mode, which automatically restarts the app when files change. Use `--watch` for general watching, or `pm2 stop --watch ` to stop watching. ```bash $pm2 start app.js --watch ``` -------------------------------- ### Execute PM2 API Script Source: https://github.com/unitech/pm2/blob/master/examples/api-pm2/README.md Run a Node.js script that utilizes the PM2 API. This example will delete all existing apps, start 'http.js', and then restart it. The expected outcome is that 'http' will be listed as an online application with one restart. ```bash $ node api.js ``` -------------------------------- ### Manage PM2 Modules Source: https://github.com/unitech/pm2/wiki/Modules Commands for installing, updating, restarting, describing, generating, and uninstalling PM2 modules. ```bash # Install $ pm2 install # Update a module $ pm2 install # Install a module from GitHub (username/repository) $ pm2 install pm2-hive/pm2-docker # Force module restart $ pm2 restart # Get more informations $ pm2 describe # Install a module in dev mode from local folder $ pm2 install . # Generate a module boilerplate $ pm2 module:generate # Uninstall module $ pm2 uninstall # Publish new module (Inc Semver + Git push + NPM publish) $ pm2 publish ``` -------------------------------- ### Generate Ecosystem Configuration File Source: https://github.com/unitech/pm2/wiki/Deployment Run this command in your project's root directory to create a sample ecosystem.json file. This file defines your applications and deployment environments. ```bash $ pm2 ecosystem ``` -------------------------------- ### Start Application Without Auto-Restart Source: https://github.com/unitech/pm2/wiki/Home Starts an application and disables the automatic restart feature. ```bash $ pm2 start app.js --no-autorestart ``` -------------------------------- ### Generate PM2 Startup Script Source: https://github.com/unitech/pm2/wiki/Home Generates and installs a startup script to ensure PM2 processes are restarted automatically on server boot or reboot. ```bash $ pm2 startup ``` -------------------------------- ### Install Latest PM2 Version Source: https://github.com/unitech/pm2/wiki/Updating-PM2 Install the most recent version of PM2 globally using NPM. ```bash $ npm install pm2 -g ``` -------------------------------- ### Run Multiple PM2 Instances Source: https://github.com/unitech/pm2/wiki/Home Start separate PM2 instances by setting the PM2_HOME environment variable to different directories. This allows managing distinct sets of processes independently. ```bash $ PM2_HOME='.pm2' pm2 start echo.js --name="echo-node-1" $ PM2_HOME='.pm3' pm2 start echo.js --name="echo-node-2" ``` ```bash $ PM2_HOME='.pm2' pm2 list $ PM2_HOME='.pm3' pm2 list ``` -------------------------------- ### PM2 Deploy Commands Source: https://github.com/unitech/pm2/wiki/Home This section outlines the various commands available for managing deployments with PM2, including setup, update, revert, and execution of remote commands. ```bash Commands: setup run remote setup commands update update deploy to the latest release revert [n] revert to [n]th last deployment or 1 curr[ent] output current release commit prev[ious] output previous release commit exec|run execute the given list list previous deploy commits [ref] deploy to [ref], the "ref" setting, or latest tag ``` -------------------------------- ### Install PM2 Globally Source: https://github.com/unitech/pm2/wiki/Home Installs the latest stable version of PM2 globally on your system using NPM. ```bash $ npm install pm2@latest -g ``` -------------------------------- ### Start PM2 Application from JSON via Stdout Pipe Source: https://github.com/unitech/pm2/wiki/Home Provide a JSON configuration to PM2 via standard input. This is useful for dynamically generating configurations or integrating with scripting. ```bash #!/bin/bash read -d '' my_json <<_EOF_ [{ "name" : "app1", "script" : "/home/projects/pm2_nodetest/app.js", "instances" : "4", "error_file" : "./logz/child-err.log", "out_file" : "./logz/child-out.log", "pid_file" : "./logz/child.pid", "exec_mode" : "cluster_mode", "port" : 4200 }] _EOF_ echo $my_json | pm2 start - ``` -------------------------------- ### Startup and Boot Management with PM2 Source: https://github.com/unitech/pm2/blob/master/pres/TMP.md Configure PM2 to start automatically on system boot, save the current process list, and restore processes. Also includes commands to disable startup. ```bash $ pm2 startup # Detect init system, generate and configure pm2 boot on startup ``` ```bash $ pm2 save # Save current process list ``` ```bash $ pm2 resurrect # Restore previously saved processes ``` ```bash $ pm2 unstartup # Disable and remove startup system ``` ```bash $ pm2 update # Save processes, kill PM2 and restore processes ``` ```bash $ pm2 init # Generate a sample js configuration file ``` -------------------------------- ### Start Application Without Vizion Source: https://github.com/unitech/pm2/wiki/Home Starts an application without enabling Vizion, a feature for monitoring and managing applications. ```bash $ pm2 start app.js --no-vizion ``` -------------------------------- ### PM2 Deploy Help and Commands Source: https://github.com/unitech/pm2/wiki/Deployment Display available deployment commands and their usage. This includes options for setup, update, revert, checking commit status, executing custom commands, and listing deployment history. ```bash $ pm2 deploy Commands: setup run remote setup commands update update deploy to the latest release revert [n] revert to [n]th last deployment or 1 curr[ent] output current release commit prev[ious] output previous release commit exec|run execute the given list list previous deploy commits [ref] deploy to [ref], the "ref" setting, or latest tag ``` -------------------------------- ### Install Git Changelog Generator Source: https://github.com/unitech/pm2/blob/master/CONTRIBUTING.md Install the git-changelog tool globally using npm, which is required for generating the changelog. ```bash npm install git-changelog -g ``` -------------------------------- ### Specify PM2 Startup Platform Source: https://github.com/unitech/pm2/wiki/Start-PM2-at-Startup Manually specify the platform for generating the startup script if auto-detection is not desired. ```bash $ pm2 startup [ubuntu | ubuntu14 | ubuntu12 | centos | centos6 | arch | oracle | amazon | macos | darwin | freesd | systemd | systemv | upstart | launchd | rcd] ``` -------------------------------- ### Install PM2 Globally in Dockerfile Source: https://github.com/unitech/pm2/wiki/Docker-Integration Installs PM2 globally within a Docker image. This is a prerequisite for using `pm2-docker`. ```dockerfile RUN npm install pm2 -g ``` -------------------------------- ### Sample ecosystem.json Configuration Source: https://github.com/unitech/pm2/wiki/Home This JSON file defines multiple applications with their respective configurations, including names, scripts, arguments, watch settings, environment variables, and more. It demonstrates how to declare different applications within a single file. ```json { "apps" : [{ // Application #1 "name" : "worker-app", "script" : "worker.js", "args" : ["--toto=heya coco", "-d", "1"], "watch" : true, "node_args" : "--harmony", "merge_logs" : true, "cwd" : "/this/is/a/path/to/start/script", "env": { "NODE_ENV": "development", "AWESOME_SERVICE_API_TOKEN": "xxx" }, "env_production" : { "NODE_ENV": "production" }, "env_staging" : { "NODE_ENV" : "staging", "TEST" : true } },{ // Application #2 "name" : "api-app", "script" : "api.js", "instances" : 4, "exec_mode" : "cluster_mode", "error_file" : "./examples/child-err.log", "out_file" : "./examples/child-out.log", "pid_file" : "./examples/child.pid" }] } ``` -------------------------------- ### Initialize Remote Deployment Folder Source: https://github.com/unitech/pm2/wiki/Deployment This command sets up the necessary directory structure on your remote server for deployment. Replace `` and `` with your specific file and environment names. ```bash $ pm2 deploy setup ``` ```bash $ pm2 deploy ecosystem.json production setup ``` -------------------------------- ### Start Application with Name in Fork Mode Source: https://github.com/unitech/pm2/wiki/Home Starts an application in fork mode and assigns a specific name to the process for easier identification. ```bash $ pm2 start app.js --name my-api ``` -------------------------------- ### Configure Startup Script for Specific User Source: https://github.com/unitech/pm2/wiki/Start-PM2-at-Startup Generates a startup script that will be executed under a specified user and home directory. ```bash $ pm2 startup ubuntu -u www --hp /home/ubuntu ``` -------------------------------- ### Generate Startup Script Programmatically Source: https://github.com/unitech/pm2/wiki/Home Use `pm2.startup` to generate a startup script for a given platform. ```javascript pm2.startup(platform, fn(err, ret){}) ``` -------------------------------- ### Generate PM2 Startup Script Source: https://github.com/unitech/pm2/wiki/Start-PM2-at-Startup Detects the init system, generates the configuration, and enables the startup script for your OS. Run this command as root. ```bash # Detect available init system, generate configuration and enable startup system $ pm2 startup ``` -------------------------------- ### PM2 Deploy Help Source: https://github.com/unitech/pm2/wiki/Home Display available commands and usage information for the `pm2 deploy` command. ```bash $ pm2 deploy help ``` -------------------------------- ### Install PM2 Auto Completion Source: https://github.com/unitech/pm2/wiki/Home Installs shell auto-completion for PM2 commands, which helps in autocompleting commands, application names, and related options. ```bash $ pm2 completion install ``` -------------------------------- ### Memory Unit Examples Source: https://github.com/unitech/pm2/wiki/Application-Monitoring Examples of valid units for specifying memory limits in PM2. Units can be Kilobytes (K), Megabytes (M), or Gigabytes (G). ```plaintext 50M 50K 1G ``` -------------------------------- ### Sample Ecosystem.json Configuration Source: https://github.com/unitech/pm2/wiki/Deployment This JSON file defines applications to be managed by PM2 and deployment configurations for different environments like production and staging. It includes settings for hosts, repositories, paths, and pre/post deployment commands. ```javascript { // Applications part "apps" : [{ "name" : "API", "script" : "app.js", "env": { "COMMON_VARIABLE": "true" }, // Environment variables injected when starting with --env production // http://pm2.keymetrics.io/docs/usage/application-declaration/#switching-to-different-environments "env_production" : { "NODE_ENV": "production" } },{ "name" : "WEB", "script" : "web.js" }], // Deployment part // Here you describe each environment "deploy" : { "production" : { "user" : "node", // Multi host is possible, just by passing IPs/hostname as an array "host" : ["212.83.163.1", "212.83.163.2", "212.83.163.3"], // Branch "ref" : "origin/master", // Git repository to clone "repo" : "git@github.com:repo.git", // Path of the application on target servers "path" : "/var/www/production", // Can be used to give options in the format used in the configura- // tion file. This is useful for specifying options for which there // is no separate command-line flag, see 'man ssh' // can be either a single string or an array of strings "ssh_options": "StrictHostKeyChecking=no", // To prepare the host by installing required software (eg: git) // even before the setup process starts // can be multiple commands separated by the character ";" // or path to a script on your local machine "pre-setup" : "apt-get install git", // Commands / path to a script on the host machine // This will be executed on the host after cloning the repository // eg: placing configurations in the shared dir etc "post-setup": "ls -la", // Commands to execute locally (on the same machine you deploy things) // Can be multiple commands separated by the character ";" "pre-deploy-local" : "echo 'This is a local executed command'" // Commands to be executed on the server after the repo has been cloned "post-deploy" : "npm install && pm2 startOrRestart ecosystem.json --env production" // Environment variables that must be injected in all applications on this env "env" : { "NODE_ENV": "production" } }, "staging" : { "user" : "node", "host" : "212.83.163.1", "ref" : "origin/master", "repo" : "git@github.com:repo.git", "path" : "/var/www/development", "ssh_options": ["StrictHostKeyChecking=no", "PasswordAuthentication=no"], "post-deploy" : "pm2 startOrRestart ecosystem.json --env dev", "env" : { "NODE_ENV": "staging" } } } } ``` -------------------------------- ### PM2 Process Configuration File Example Source: https://github.com/unitech/pm2/wiki/Docker-Integration Defines application settings for PM2, including script paths, names, execution mode, and instance count. This file is used by `pm2-docker` to manage applications. ```yaml apps: - script : 'app.js' name : 'APP' exec_mode: 'cluster' instances: 4 - script : 'worker.js' ``` -------------------------------- ### Red Hat/CentOS PM2 Installation Source: https://github.com/unitech/pm2/blob/master/test/README.md Steps for installing PM2 on Red Hat-based systems, including system dependencies, Node Version Manager (nvm), and PM2 itself. ```bash $ sudo yum install git wget emacs $ sudo yum groupinstall "Development Tools" $ wget -qO- https://raw.github.com/creationix/nvm/master/install.sh | sh $ # put .bash_profile content to .bashrc $ source .bashrc $ nvm install v0.11.10 $ nvm alias default 0.11.10 $ npm install pm2 -g $ # OR $ npm install git://github.com/Unitech/pm2.git#development -g ``` -------------------------------- ### Configuring Args and Node Args as String Source: https://github.com/unitech/pm2/wiki/Home Demonstrates defining 'args' and 'node_args' as a single string in the PM2 JSON configuration. ```json "args": "--to='heya coco' -d 1" ``` ```json "node_args": "--to='heya coco' -d 1" ``` -------------------------------- ### Launch Interactor Client Source: https://github.com/unitech/pm2/blob/master/modules/pm2-io-agent/README.md Use src/InteractorClient.js and the launchAndInteract method to start the agent. Provide an empty object for constants, an options object with keys for secret_key, public_key, and machine_name, and a callback function. ```javascript const InteractorClient = require('keymetrics-agent/src/InteractorClient') InteractorClient.launchAndInteract({}, { secret_key: '', public_key: '', machine_name: '' }, (err, msg) => { }) ``` -------------------------------- ### Graceful Start: Signal Readiness Source: https://github.com/unitech/pm2/wiki/Graceful-Start-Stop For graceful starts, signal PM2 that your application is ready by sending the 'ready' message. This is useful when your application needs to establish connections before being considered online. ```javascript var http = require('http'); var app = http.createServer(function(req, res) { res.writeHead(200); res.end('hey'); }) var listener = app.listen(0, function() { console.log('Listening on port ' + listener.address().port); process.send('ready'); }); ``` -------------------------------- ### Register with Keymetrics Source: https://github.com/unitech/pm2/blob/master/examples/test-all-keymetrics-features/README.md Run this command to register your PM2 instance with Keymetrics. Ensure you have a Keymetrics account first. ```bash $ pm2 register ``` -------------------------------- ### Configure PM2 Home Directory Source: https://github.com/unitech/pm2/blob/master/test/README.md Set the PM2_HOME environment variable and create the necessary directory with appropriate permissions for PM2 to store its data. ```bash $ sudo sh -c 'echo "export PM2_HOME=/var/" >> /etc/profile' $ sudo mkdir /var/.pm2; chown -R tknew:tknew /var/.pm2 ``` -------------------------------- ### Install PM2 Tab Completion Source: https://github.com/unitech/pm2/wiki/Home Instructions for installing PM2 tab completion for your shell. This can be done automatically or manually by appending the completion script to your shell's configuration file. ```bash $ pm2 completion install # Or manually append completion script to your ~/.bashrc or ~/.zshrc file: $ pm2 completion >> ~/.bashrc # or ~/.zshrc # Then source your .bashrc or .zshrc file for current session: $ source ~/.bashrc # or ~/.zshrc # You can add pm2 completion to your current session this way: $ . <(pm2 completion) ``` -------------------------------- ### PM2 Programmatic Interface Example Source: https://github.com/unitech/pm2/wiki/Home An example of how to use PM2 programmatically within a Node.js application, suitable for deployment on platforms like Heroku, Google App Engine, or Azure. ```javascript var pm2 = require('pm2'); pm2.connect(function(err) { if (err) { console.error(err); process.exit(2); } pm2.start({ script : 'app.js', exec_mode : 'cluster', instances : 'max', max_memory_restart : '100M' }, function(err, apps) { if (err) return console.error('Error while trying to run the pm2.start API...', err.message || err); console.log('PM2 and application started'); // Insert here, the code you want to run, i.e. "pm2.disconnect();" pm2.disconnect(); }); }); ``` -------------------------------- ### Attach to a PM2 Process for Stdin Interaction Source: https://github.com/unitech/pm2/blob/master/examples/interact-via-stdin/README.md After starting an application that reads from stdin, use this command to attach to the process. Replace '0' with the actual process ID if it's not the first one started. ```bash $ pm2 attach 0 ``` -------------------------------- ### JSON Log Object Example Source: https://github.com/unitech/pm2/wiki/Log-Management An example structure of a log message when JSON log type is enabled. Includes message content, timestamp, log type, process ID, and application name. ```json { "message": "echo\n", // the acual message that has been `console.log` "timestamp": "2017-02-06T14:51:38.896Z", // timestamp of the message, can be formated "type": "out", // the type of logs, can be `err`, `out` or `PM2` "process_id": 0, // the process id used by PM2 "app_name": "one-echo" // the application name } ``` -------------------------------- ### Start Application without Keymetrics Source: https://github.com/unitech/pm2/wiki/Home Use this snippet to start a Node.js application in cluster mode without Keymetrics integration. It allows setting environment variables and configuring memory limits for automatic restarts. ```javascript var pm2 = require('pm2'); var instances = process.env.WEB_CONCURRENCY || -1; // Set by Heroku or -1 to scale to max cpu core -1 var maxMemory = process.env.WEB_MEMORY || 512; // " " " pm2.connect(function() { pm2.start({ script : 'app.js', name : 'production-app', // ----> THESE ATTRIBUTES ARE OPTIONAL: exec_mode : 'cluster', // ----> https://github.com/Unitech/PM2/blob/master/ADVANCED_README.md#schema instances : instances, max_memory_restart : maxMemory + 'M', // Auto restart if process taking more than XXmo env: { // If needed declare some environment variables "NODE_ENV": "production", "AWESOME_SERVICE_API_TOKEN": "xxx" }, }, function(err) { if (err) return console.error('Error while launching applications', err.stack || err); console.log('PM2 and application has been succesfully started'); // Display logs in standard output pm2.launchBus(function(err, bus) { console.log('[PM2] Log streaming started'); bus.on('log:out', function(packet) { console.log('[App:%s] %s', packet.process.name, packet.data); }); bus.on('log:err', function(packet) { console.error('[App:%s][Err] %s', packet.process.name, packet.data); }); }); }); }); ```