### Start an Application with PM2 Source: https://pm2.keymetrics.io/docs/usage/quick-start Start a Node.js application, daemonize it, and begin monitoring its performance. This is the most basic command to get an app running with PM2. ```bash $ pm2 start app.js ``` -------------------------------- ### Connecting and Managing Processes Source: https://pm2.keymetrics.io/docs/usage/pm2-api This example demonstrates how to connect to PM2, start an application, list all managed applications, restart a specific application, and finally disconnect from PM2. ```APIDOC ## PM2 Javascript API Usage ### Description This section provides an example of using the PM2 Javascript API to manage application processes. It covers connecting to PM2, starting a script, listing all running applications, restarting a specific application by name, and disconnecting from the PM2 daemon. ### Methods - `pm2.connect()`: Establishes a connection to the local PM2 daemon. - `pm2.start(options, callback)`: Starts a new application. `options` can include `script` and `name`. `callback` is executed after the application starts. - `pm2.list(callback)`: Retrieves a list of all applications currently managed by PM2. The `callback` receives an error and the list of applications. - `pm2.restart(name, callback)`: Restarts the application identified by `name`. The `callback` is executed after the restart attempt. - `pm2.disconnect()`: Disconnects from the PM2 daemon. ### Code Example ```javascript const pm2 = require('pm2'); pm2.connect(function(err) { if (err) { console.error(err); process.exit(2); } pm2.start({ script : 'api.js', name : 'api' }, function(err, apps) { if (err) { console.error(err); return pm2.disconnect(); } console.log('Application started:', apps); pm2.list((err, list) => { if (err) { console.error(err); return pm2.disconnect(); } console.log('Current PM2 list:', list); pm2.restart('api', (err, proc) => { if (err) { console.error(err); } else { console.log('Application restarted:', proc); } pm2.disconnect(); }); }); }); }); ``` ### Notes - Ensure PM2 is installed globally (`npm install pm2 -g`) and the `pm2` module is added as a dependency to your project (`npm install pm2 --save`). - The `pm2.disconnect()` call is crucial to release the connection and allow the script to exit cleanly. ``` -------------------------------- ### PM2 API Quickstart Script Source: https://pm2.keymetrics.io/docs/usage/pm2-api Connect to PM2, start a script, list all managed applications, restart a specific application, and then disconnect from PM2. ```javascript const pm2 = require('pm2') pm2.connect(function(err) { if (err) { console.error(err) process.exit(2) } pm2.start({ script : 'api.js', name : 'api' }, function(err, apps) { if (err) { console.error(err) return pm2.disconnect() } pm2.list((err, list) => { console.log(err, list) pm2.restart('api', (err, proc) => { // Disconnects from PM2 pm2.disconnect() }) }) }) }) ``` -------------------------------- ### Start Applications using Ecosystem File Source: https://pm2.keymetrics.io/docs/usage/pm2-doc-single-page Start multiple applications defined in an ecosystem configuration file using the `pm2 start` command. ```bash $ pm2 start process.yml ``` -------------------------------- ### Provision Remote Server Source: https://pm2.keymetrics.io/docs/usage/deployment Command to initiate the setup process on remote servers, ensuring PM2 is installed and Git permissions are granted. ```bash $ pm2 deploy production setup ``` -------------------------------- ### Start Application with PM2 Source: https://pm2.keymetrics.io/docs/usage/process-metrics Start your application with PM2 after it has been configured to expose metrics. ```bash $ pm2 start monit.js ``` -------------------------------- ### Starting PM2 with Environment Override Source: https://pm2.keymetrics.io/docs/usage/pm2-doc-single-page Demonstrates how to start PM2 applications using a process file and override the environment settings. ```bash pm2 start ecosystem.json --env production ``` -------------------------------- ### Configure and Start Multiple Applications Source: https://pm2.keymetrics.io/docs/usage/pm2-doc-single-page Define multiple applications with their configurations in an ecosystem file and start them using PM2. ```javascript module.exports = { apps : [{ name : "limit worker", script : "./worker.js", args : "limit" },{ name : "rotate worker", script : "./worker.js", args : "rotate" }] } ``` ```bash $ pm2 start ecosystem.config.js ``` -------------------------------- ### Deployment Configuration Example Source: https://pm2.keymetrics.io/docs/usage/deployment Example of how to configure deployment settings within an application's configuration file (ecosystem.config.js or pm2.config.js). ```javascript module.exports = { apps : [{ script: 'api.js', }, { script: 'worker.js' }], // Deployment Configuration deploy : { production : { "user" : "ubuntu", "host" : ["192.168.0.13", "192.168.0.14", "192.168.0.15"], "ref" : "origin/master", "repo" : "git@github.com:Username/repository.git", "path" : "/var/www/my-repository", "post-deploy" : "npm install" } } }; ``` -------------------------------- ### Configure package.json start script Source: https://pm2.keymetrics.io/docs/integrations/heroku Modify the 'start' script in package.json to use pm2-runtime for starting your application in production environment. ```json { "scripts": { "start": "pm2-runtime start ecosystem.config.js --env production" } } ``` -------------------------------- ### Start Application with PM2 Source: https://pm2.keymetrics.io/docs/usage/process-actions Start the RPC-enabled application using PM2. ```bash $ pm2 start rpc.js ``` -------------------------------- ### Pass Arguments to Started Application Source: https://pm2.keymetrics.io/docs/usage/process-management Arguments specified after `--` in the start command will be passed directly to your application. ```bash $ pm2 start api.js -- arg1 arg2 ``` -------------------------------- ### Install tx2 Module Source: https://pm2.keymetrics.io/docs/usage/process-metrics Install the tx2 module, which is required for exposing custom metrics. ```bash $ npm install tx2 ``` -------------------------------- ### Start pm2-runtime with Keymetrics CLI options Source: https://pm2.keymetrics.io/docs/usage/docker-pm2-nodejs Use this command in a Dockerfile to start pm2-runtime with Keymetrics monitoring enabled via CLI arguments. ```docker CMD ["pm2-runtime", "--public", "XXX", "--secret", "YYY", "process.yml"] ``` -------------------------------- ### Start Applications Using Configuration File Source: https://pm2.keymetrics.io/docs/usage/process-management Initiate multiple applications defined in an ecosystem configuration file with a single command. ```bash $ pm2 start ecosystem.config.js ``` -------------------------------- ### Start Application in Fork Mode Source: https://pm2.keymetrics.io/docs/usage/quick-start Use this command to start a single instance of your application. You can optionally name the process. ```bash pm2 start app.js --name my-api ``` -------------------------------- ### Install Node.js Dependencies for Testing on Ubuntu Source: https://pm2.keymetrics.io/docs/usage/pm2-doc-single-page Install build essentials, nvm, and a specific Node.js version for testing PM2. ```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 4 nvm use 4 ``` -------------------------------- ### Start Application Using Configuration File Source: https://pm2.keymetrics.io/docs/usage/cluster-mode Initiate your application using a JSON configuration file that specifies cluster mode and other settings. ```bash pm2 start processes.json ``` -------------------------------- ### Starting PM2 from Project Root Source: https://pm2.keymetrics.io/docs/tutorials/capistrano-like-deployments Demonstrates the command to start or restart a PM2 application using an ecosystem file, executed from the project's root directory. ```bash # somewhere in your deployment script cd /home/www/project_root pm2 startOrRestart current/ecosystem.json ``` -------------------------------- ### Expose Request Metrics with tx2 Source: https://pm2.keymetrics.io/docs/usage/pm2-doc-single-page Install the tx2 module and use it to expose request per second metrics for an HTTP server. Start the application with PM2. ```bash $ npm install tx2 ``` ```javascript const tx2 = require('tx2') const http = require('http') let meter = tx2.meter({ name : 'req/sec', samples : 1, timeframe : 60 }) http.createServer((req, res) => { meter.mark() res.writeHead(200, {'Content-Type': 'text/plain'}) res.write('Hello World!') res.end() }).listen(6001) ``` ```bash $ pm2 start monit.js ``` -------------------------------- ### Example PM2 Remote Command Execution Source: https://pm2.keymetrics.io/docs/tutorials/capistrano-like-deployments Illustrates the actual command executed on the remote server for starting or restarting a PM2 application. It includes environment variables and the path to the ecosystem file. ```bash SOME_APP_ENV="production" cd /home/www/project_root && pm2 startOrRestart --env production current/ecosystem.json` ``` -------------------------------- ### Ecosystem File Configuration Example Source: https://pm2.keymetrics.io/docs/usage/quick-start An example of an `ecosystem.config.js` file defining two applications with different configurations, including environment variables for development and production. ```javascript module.exports = { apps : [{ name: "app", script: "./app.js", env: { NODE_ENV: "development", }, env_production: { NODE_ENV: "production", } }, { name: 'worker', script: 'worker.js' }] } ``` -------------------------------- ### Install tx2 Module Source: https://pm2.keymetrics.io/docs/usage/process-actions Install the tx2 module using npm. This is required to expose RPC methods. ```bash $ npm install tx2 ``` -------------------------------- ### Install PM2 Repository and Package Source: https://pm2.keymetrics.io/docs/usage/pm2-doc-single-page Steps to add the PM2 repository and install the PM2 package on a Debian-based system. ```bash echo "deb http://apt.pm2.io/ubuntu stable main" | sudo tee /etc/apt/sources.list.d/pm2.list ``` ```bash sudo apt-get update ``` ```bash sudo apt-get install pm2 ``` -------------------------------- ### Start an Application with PM2 Source: https://pm2.keymetrics.io/docs/usage/process-management Use this command to start a Node.js application. The application will run in the background. ```bash $ pm2 start api.js ``` -------------------------------- ### Install and Configure Authbind for Port 80 Source: https://pm2.keymetrics.io/docs/usage/pm2-doc-single-page Install authbind and configure it to allow a non-root user to bind to port 80. Replace %user% with the actual username. ```bash sudo apt-get install authbind sudo touch /etc/authbind/byport/80 sudo chown %user% /etc/authbind/byport/80 sudo chmod 755 /etc/authbind/byport/80 ``` -------------------------------- ### Start Various Application Types Source: https://pm2.keymetrics.io/docs/usage/process-management PM2 can start not only Node.js applications but also bash commands, scripts, and binaries. ```bash $ pm2 start "npm run start" ``` ```bash $ pm2 start "ls -la" ``` ```bash $ pm2 start app.py ``` -------------------------------- ### Install PM2 Package Source: https://pm2.keymetrics.io/docs/usage/install-as-deb Installs the PM2 process manager from the configured repositories. This command fetches and installs the pm2 package and its dependencies. ```bash sudo apt-get install pm2 ``` -------------------------------- ### Start Application in Cluster Mode Source: https://pm2.keymetrics.io/docs/usage/quick-start Start your application with multiple instances for load balancing. '-i 0' or '-i max' will use all available CPU cores. ```bash pm2 start app.js -i 0 ``` ```bash pm2 start app.js -i max ``` -------------------------------- ### SystemD Installation Checking Commands Source: https://pm2.keymetrics.io/docs/usage/startup Commands to verify the SystemD service installation, check logs, view the configuration file, and analyze startup performance. ```bash # Check if pm2- service has been added $ systemctl list-units ``` ```bash # Check logs $ journalctl -u pm2- ``` ```bash # Cat systemd configuration file $ systemctl cat pm2- ``` ```bash # Analyze startup $ systemd-analyze plot > output.svg ``` -------------------------------- ### Clone PM2 and Run Tests Source: https://pm2.keymetrics.io/docs/usage/contributing Clone the PM2 repository, install dependencies, and run the test suite. Ensure all necessary system dependencies are 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 ``` -------------------------------- ### PM2 Configuration File Example Source: https://pm2.keymetrics.io/docs/usage/process-management Manage multiple applications or specify complex options using a configuration file (ecosystem.config.js). This example defines two worker applications with different arguments. ```javascript module.exports = { apps : [{ name : "limit worker", script : "./worker.js", args : "limit" },{ name : "rotate worker", script : "./worker.js", args : "rotate" }] } ``` -------------------------------- ### Install PM2 Development Version Source: https://pm2.keymetrics.io/docs/usage/contributing Install PM2 directly from the development branch on GitHub globally. ```bash npm install https://github.com/Unitech/pm2#development -g ``` -------------------------------- ### Start Application in Development Mode with PM2 Source: https://pm2.keymetrics.io/docs/usage/pm2-development Use `pm2-dev` to start your application. It will print logs and automatically restart the application when files change. ```bash pm2-dev start my-app.js ``` ```bash pm2-dev my-app.js ``` -------------------------------- ### Start Application with Wait Ready Flag Source: https://pm2.keymetrics.io/docs/usage/signals-clean-restart Initiate your application with the `--wait-ready` flag to enable PM2's graceful start mechanism. This requires the application to send a 'ready' signal. ```bash pm2 start app.js --wait-ready ``` -------------------------------- ### Install PM2 Development Version Source: https://pm2.keymetrics.io/docs/usage/pm2-doc-single-page Install the development version of PM2 globally using npm. ```bash npm install https://github.com/Unitech/pm2#development -g ``` -------------------------------- ### PM2 Start Command Options Source: https://pm2.keymetrics.io/docs/usage/quick-start Explore common options for the `pm2 start` command to customize application management, such as naming, watching for changes, setting memory limits, specifying log files, and passing arguments. ```bash # Specify an app name --name # Watch and Restart app when files change --watch # Set memory threshold for app reload --max-memory-restart <200MB> # Specify log file --log # Pass extra arguments to the script -- arg1 arg2 arg3 # Delay between automatic restarts --restart-delay # Prefix logs with time --time # Do not auto restart app --no-autorestart # Specify cron for forced restart --cron # Attach to application log --no-daemon ``` -------------------------------- ### Configuring args, node_args, and ignore_watch as Array or String Source: https://pm2.keymetrics.io/docs/usage/pm2-doc-single-page Shows examples of how 'args', 'node_args', and 'ignore_watch' can be configured as either an array or a string. ```json "args": ["--toto=heya coco", "-d", "1"] ``` ```json "args": "--to='heya coco' -d 1" ``` -------------------------------- ### Start Application and Stream Logs Source: https://pm2.keymetrics.io/docs/usage/process-management To start an application and simultaneously view its logs in the terminal, use the `--attach` option. Press Ctrl+C to detach, and the application will continue running in the background. ```bash $ pm2 start api.js --attach ``` -------------------------------- ### Start an application with timestamp prefixing Source: https://pm2.keymetrics.io/docs/usage/log-management Enable automatic timestamp prefixing for application logs by using the `--time` flag when starting the application. ```bash $ pm2 start app.js --time ``` -------------------------------- ### Install Latest PM2 Version Source: https://pm2.keymetrics.io/docs/usage/update-pm2 Use this command to install the latest version of PM2 globally. ```bash npm install pm2 -g ``` -------------------------------- ### Start Application from JSON configuration via Pipe Source: https://pm2.keymetrics.io/docs/usage/specifics Pipe a JSON configuration string to PM2 to start applications, useful for dynamic configuration or 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 - ``` -------------------------------- ### Install the pm2-logrotate module Source: https://pm2.keymetrics.io/docs/usage/log-management Install the pm2-logrotate module to automatically rotate and manage log files, conserving disk space. ```bash pm2 install pm2-logrotate ``` -------------------------------- ### Initialize PM2 Module Source: https://pm2.keymetrics.io/docs/advanced/pm2-module-system Example of initializing a PM2 module in its main entry point using pmx.initModule. Allows overriding the PID to be monitored. ```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); }); ``` -------------------------------- ### Install PM2 CLI Completion Source: https://pm2.keymetrics.io/docs/usage/auto-completion Run this command to automatically install PM2's CLI completion scripts. ```bash pm2 completion install ``` -------------------------------- ### Clone PM2 and Run Tests Source: https://pm2.keymetrics.io/docs/usage/pm2-doc-single-page Clone the PM2 repository, install dependencies, and run the test suite. ```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 ``` -------------------------------- ### Generate and Install a Module Source: https://pm2.keymetrics.io/docs/advanced/pm2-module-system Steps to generate a new PM2 module boilerplate and then install it locally for development. PM2 automatically restarts the module on changes when in watch mode. ```bash pm2 module:generate cd pm2 install . ``` -------------------------------- ### Start Application with Watch Mode Source: https://pm2.keymetrics.io/docs/usage/pm2-doc-single-page Start your application with PM2 and enable watch mode to automatically restart the app on file changes. ```bash pm2 start app.js --watch ``` -------------------------------- ### Start Application Without Daemonization Source: https://pm2.keymetrics.io/docs/usage/quick-start Start an application without running it as a background daemon. Useful for debugging or specific environments. ```bash pm2 start app.js --no-daemon ``` ```bash pm2 start app.js --no-vizion ``` ```bash pm2 start app.js --no-autorestart ``` -------------------------------- ### PM2 Deploy Setup Command Source: https://pm2.keymetrics.io/docs/usage/pm2-doc-single-page Provision a remote server for PM2 deployment. ```bash $pm2 deploy production setup ``` -------------------------------- ### Start Application with Custom Log File Paths (CLI) Source: https://pm2.keymetrics.io/docs/usage/pm2-doc-single-page When starting an application via the CLI, you can specify custom file paths for standard output and error logs using the `-o` and `-e` flags, respectively. ```bash pm2 start app.js -o /path/to/out.log -e /path/to/error.log ``` -------------------------------- ### pm2.start Source: https://pm2.keymetrics.io/docs/usage/pm2-api Starts a new process managed by PM2. This can be a script file or a configuration object. ```APIDOC ## pm2.start(process, fn) ### Description Start a process managed by PM2. ### Parameters #### Path Parameters - **process** (string/object) - The script path (relative) or an options object. - **fn** (function) - Callback function. ``` -------------------------------- ### Install Node.js Dependencies for Ubuntu Source: https://pm2.keymetrics.io/docs/usage/contributing Install build essentials and set up Node.js version management using nvm on Ubuntu. This is a prerequisite for running PM2 development and tests. ```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 4 nvm use 4 ``` -------------------------------- ### Multi-Host Deployment Configuration Source: https://pm2.keymetrics.io/docs/usage/deployment Example of configuring deployment to multiple hosts by providing an array of IP addresses or hostnames under the 'host' attribute. ```json "host" : ["212.83.163.1", "212.83.163.2", "212.83.163.3"], ``` -------------------------------- ### Manage Applications from Configuration File Source: https://pm2.keymetrics.io/docs/usage/pm2-doc-single-page Start, stop, restart, reload, or delete all applications defined in a PM2 configuration file. ```bash pm2 start ecosystem.config.js ``` ```bash pm2 stop ecosystem.config.js ``` ```bash pm2 restart ecosystem.config.js ``` ```bash pm2 reload ecosystem.config.js ``` ```bash pm2 delete ecosystem.config.js ``` -------------------------------- ### PM2 Deployment Configuration Source: https://pm2.keymetrics.io/docs/usage/pm2-doc-single-page Example ecosystem.json configuration for deploying an application with PM2. ```json module.exports = { apps : [{ script: 'api.js', }, { script: 'worker.js' }], // Deployment Configuration deploy : { production : { "user" : "ubuntu", "host" : ["192.168.0.13", "192.168.0.14", "192.168.0.15"], "ref" : "origin/master", "repo" : "git@github.com:Username/repository.git", "path" : "/var/www/my-repository", "post-deploy" : "npm install" } } }; ``` -------------------------------- ### Manage PM2 Modules Source: https://pm2.keymetrics.io/docs/advanced/pm2-module-system Commands for installing, updating, restarting, describing, and uninstalling PM2 modules. Supports installation from NPM, GitHub, and local folders. ```bash pm2 install pm2 install pm2 install pm2-hive/pm2-docker pm2 restart pm2 describe pm2 install . pm2 module:generate pm2 uninstall pm2 publish ``` -------------------------------- ### Capistrano Directory Structure Example Source: https://pm2.keymetrics.io/docs/tutorials/capistrano-like-deployments Illustrates a typical directory layout for Capistrano-like deployments, featuring a 'current' symlink to the active release. ```bash project_root ├── current -> releases/20150301100000 # this is a symlink to the current release └── releases ├── 20150301100000 ├── 20150228100000 └── 20150226100000 ``` -------------------------------- ### Integrate PM2 in package.json Source: https://pm2.keymetrics.io/docs/tutorials/use-pm2-with-aws-elastic-beanstalk Modify package.json scripts to use PM2 for starting and logging your application. Ensure PM2 is installed as a dependency. ```json "scripts": { "start": "./node_modules/pm2/bin/pm2-runtime app.js", "poststart": "node ./node_modules/pm2/bin/pm2 logs" } ``` -------------------------------- ### Integrate PM2 in package.json for Elastic Beanstalk Source: https://pm2.keymetrics.io/docs/usage/pm2-doc-single-page Modify your package.json to use PM2 as a runtime to start your application. This requires installing PM2 as a dependency. ```json "scripts": { "start": "./node_modules/pm2/bin/pm2-runtime app.js", "poststart": "node ./node_modules/pm2/bin/pm2 logs" } ``` -------------------------------- ### Start Application with Max Memory Restart (CLI) Source: https://pm2.keymetrics.io/docs/usage/memory-limit Use the `--max-memory-restart` flag when starting an application via the CLI to set a memory limit. If the limit is exceeded, the application will be reloaded. ```bash pm2 start api.js --max-memory-restart 300M ``` -------------------------------- ### Start pm2-runtime with Keymetrics environment variables via Docker run Source: https://pm2.keymetrics.io/docs/usage/docker-pm2-nodejs Enable Keymetrics monitoring when running a Docker container by passing the public and secret keys as environment variables. ```bash docker run --net host -e "PM2_PUBLIC_KEY=XXX" -e "PM2_SECRET_KEY=XXX" <...> ``` -------------------------------- ### Implement Graceful Start with 'ready' Event Source: https://pm2.keymetrics.io/docs/usage/signals-clean-restart Signal PM2 that your application is ready after establishing necessary connections (e.g., to databases or caches). PM2 will wait for this signal before considering the application '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) // Here we send the ready signal to PM2 process.send('ready') }) ``` -------------------------------- ### Switch Environment Variables for Applications Source: https://pm2.keymetrics.io/docs/usage/pm2-doc-single-page Start or restart applications using a specific environment configuration defined in the PM2 configuration file. ```bash pm2 start process.json --env production ``` ```bash pm2 restart process.json --env development ``` -------------------------------- ### Run PM2 Runtime with Ecosystem File Source: https://pm2.keymetrics.io/docs/usage/docker-pm2-nodejs Use `pm2-runtime` with a process configuration file (e.g., `process.yml`) to start your applications. This allows for more complex configurations than direct script execution. ```dockerfile CMD ["pm2-runtime", "process.yml"] ``` -------------------------------- ### Start Application in Cluster Mode Source: https://pm2.keymetrics.io/docs/usage/cluster-mode Use the `-i` flag with `max` to automatically scale your application across all available CPU cores. This is the simplest way to enable cluster mode. ```bash pm2 start app.js -i max ``` -------------------------------- ### Start CoffeeScript with PM2 Source: https://pm2.keymetrics.io/docs/tutorials/using-transpilers-with-pm2 Use the `--interpreter` flag to specify `coffee` as the interpreter for PM2. This command only works in `fork_mode`. ```bash #- npm install -g coffee-script #- pm2 start --interpreter coffee index.coffee ``` -------------------------------- ### Show Available RPC Methods Source: https://pm2.keymetrics.io/docs/usage/process-actions List all available RPC methods for a given application using the 'pm2 show' command. ```bash pm2 show # pm2 show rpc ``` -------------------------------- ### Procfile for Elastic Beanstalk Source: https://pm2.keymetrics.io/docs/tutorials/use-pm2-with-aws-elastic-beanstalk Specify the command to start your application on Elastic Beanstalk by creating a Procfile. ```bash web: npm start ``` -------------------------------- ### Enable Source Map Support via CLI Source: https://pm2.keymetrics.io/docs/usage/source-map-support Use this command to start your application with source map support enabled. PM2 will look for a .map file alongside your script. ```bash pm2 start app.js --source-map-support ``` -------------------------------- ### Start Babel with PM2 Source: https://pm2.keymetrics.io/docs/tutorials/using-transpilers-with-pm2 Use the `--interpreter` flag to specify `babel-node` as the interpreter for PM2. This command only works in `fork_mode`. ```bash #- npm install -g babel-cli #- pm2 start --interpreter babel-node index.es6 ``` -------------------------------- ### Access Module Configuration Values Source: https://pm2.keymetrics.io/docs/advanced/pm2-module-system Example of accessing the default configuration values (e.g., days_interval, max_size) that were declared in package.json after the module has been initialized. ```javascript var conf = pmx.initModule({[...]}, function(err, conf) { // Now we can read these values console.log(conf.days_interval); }); ``` -------------------------------- ### Run Multiple PM2 Instances Source: https://pm2.keymetrics.io/docs/usage/specifics Start separate PM2 instances by setting the PM2_HOME environment variable to different directories. This allows for isolated process management. ```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 ``` -------------------------------- ### Define Multiple Environment Configurations Source: https://pm2.keymetrics.io/docs/usage/environment Set up different environment configurations (e.g., development, production) in your ecosystem file. You can switch between them using the --env flag when starting PM2. ```javascript module.exports = { apps : [ { name: "myapp", script: "./app.js", watch: true, env: { "PORT": 3000, "NODE_ENV": "development" }, env_production: { "PORT": 80, "NODE_ENV": "production", } } ] } ``` -------------------------------- ### Specify Init System for Startup Script Source: https://pm2.keymetrics.io/docs/usage/startup Manually specify the init system (e.g., ubuntu, systemd, launchd) when generating the startup script. ```bash pm2 startup [ubuntu | ubuntu14 | ubuntu16 | ubuntu18 | ubuntu20 | ubuntu12 | centos | centos6 | arch | oracle | amazon | macos | darwin | freebsd | systemd | systemv | upstart | launchd | rcd | openrc] ``` -------------------------------- ### PM2 Module package.json Configuration Source: https://pm2.keymetrics.io/docs/advanced/pm2-module-system Example package.json structure for a PM2 module, including dependencies, default 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 overridden 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" } ``` -------------------------------- ### Switching Environments with PM2 Commands Source: https://pm2.keymetrics.io/docs/usage/application-declaration Use the `--env [env name]` option with PM2 commands to start or restart applications with their corresponding environment variables defined in the ecosystem file. ```bash pm2 start ecosystem.config.js --env production pm2 restart ecosystem.config.js --env development ``` -------------------------------- ### Configure Ready Timeout in Ecosystem File Source: https://pm2.keymetrics.io/docs/usage/signals-clean-restart Specify the `listen_timeout` and `wait_ready` attributes in your process configuration file for graceful start. This ensures PM2 waits the configured duration for the 'ready' signal. ```javascript module.exports = { apps : [{ name: 'app', script: './app.js', wait_ready: true, listen_timeout: 10000 }] } ``` -------------------------------- ### Watch and Restart Application on File Changes Source: https://pm2.keymetrics.io/docs/usage/quick-start Start an application with the `--watch` option to automatically restart it whenever relevant files change. Use `--ignore-watch` to exclude specific directories like `node_modules`. ```bash cd /path/to/my/app $ pm2 start env.js --watch --ignore-watch="node_modules" ``` -------------------------------- ### Create a Meter Metric Source: https://pm2.keymetrics.io/docs/usage/process-metrics Example of creating a meter metric to track requests per second for an HTTP server. The meter will record events and calculate the rate over a specified timeframe. ```javascript const tx2 = require('tx2') const http = require('http') let meter = tx2.meter({ name : 'req/sec', samples : 1, timeframe : 60 }) http.createServer((req, res) => { meter.mark() res.writeHead(200, {'Content-Type': 'text/plain'}) res.write('Hello World!') res.end() }).listen(6001) ``` -------------------------------- ### Bind to Port 80 without Root using Authbind Source: https://pm2.keymetrics.io/docs/usage/specifics Install authbind and configure permissions to allow non-root users to bind to privileged ports like 80. An alias is recommended for convenience. ```bash sudo apt-get install authbind sudo touch /etc/authbind/byport/80 sudo chown %user% /etc/authbind/byport/80 sudo chmod 755 /etc/authbind/byport/80 ``` ```bash +alias pm2='authbind --deep pm2' ``` ```bash authbind --deep pm2 update ``` -------------------------------- ### Install and Use CoffeeScript with PM2 Source: https://pm2.keymetrics.io/docs/usage/specifics Install the CoffeeScript module for PM2 to run CoffeeScript applications. Supports both CoffeeScript v1 and v2. ```bash pm2 install coffee-script pm2 start app.coffee ``` ```bash pm2 install coffeescript pm2 start app.coffee ``` -------------------------------- ### Specify Init System for PM2 Startup Source: https://pm2.keymetrics.io/docs/usage/pm2-doc-single-page Manually specify the init system (e.g., systemd, upstart, launchd) when generating the PM2 startup script if automatic detection is not desired. ```bash pm2 startup [ubuntu | ubuntu14 | ubuntu12 | centos | centos6 | arch | oracle | amazon | macos | darwin | freebsd | systemd | systemv | upstart | launchd | rcd | openrc] ``` -------------------------------- ### Generate a Simple Ecosystem Configuration File Source: https://pm2.keymetrics.io/docs/usage/application-declaration Use the `pm2 init simple` command to generate a basic `ecosystem.config.js` file. This file is used to organize and manage multiple PM2 applications. ```bash $ pm2 init simple ``` -------------------------------- ### Install PM2 Globally Source: https://pm2.keymetrics.io/docs/usage/quick-start Install the latest version of PM2 globally using NPM or Yarn. This command makes the PM2 CLI available system-wide. ```bash $ npm install pm2@latest -g # or $ yarn global add pm2 ``` -------------------------------- ### Configuration file options for log management Source: https://pm2.keymetrics.io/docs/usage/log-management Illustrates configuration file settings for specifying log file paths, merging logs, and custom date formats. ```json { "error_file": "/path/to/error.log", "out_file": "/path/to/out.log", "log_file": "/path/to/combined.log", "merge_logs": true, "log_date_format": "YYYY-MM-DD HH:mm Z", "log_type": "json" } ``` -------------------------------- ### Generate Startup Script for Specific User Source: https://pm2.keymetrics.io/docs/usage/startup Customize the startup script to run under a specific user and home directory using the `-u` and `--hp` options. ```bash pm2 startup ubuntu -u www --hp /home/ubuntu ``` -------------------------------- ### Add PM2 as a Project Dependency Source: https://pm2.keymetrics.io/docs/usage/use-pm2-with-cloud-providers Install PM2 as a local dependency in your project using npm or yarn. This is necessary for running PM2 without global installation. ```bash npm install pm2 ``` ```bash yarn add pm2 ``` -------------------------------- ### Install PM2 Globally in Docker Source: https://pm2.keymetrics.io/docs/usage/docker-pm2-nodejs Install PM2 globally within your Docker image using npm. This is a prerequisite for using PM2 in your containerized Node.js application. ```bash RUN npm install pm2 -g ``` -------------------------------- ### Generate PM2 Startup Script Source: https://pm2.keymetrics.io/docs/usage/startup Run this command to automatically detect your system's init system and generate a startup script. You may need to execute it with root privileges. ```bash $ pm2 startup ``` ```bash sudo su -c "env PATH=$PATH:/home/unitech/.nvm/versions/node/v14.3/bin pm2 startup -u --hp " ``` -------------------------------- ### Start Various Script Types Source: https://pm2.keymetrics.io/docs/usage/quick-start PM2 can start different types of scripts, including shell scripts, Python applications, and binary executables. The `--watch` option enables automatic restarts on file changes for supported script types. ```bash $ pm2 start bashscript.sh $ pm2 start python-app.py --watch $ pm2 start binary-file -- --port 1520 ``` -------------------------------- ### Uninstall Module Source: https://pm2.keymetrics.io/docs/advanced/pm2-module-system Command to remove a previously installed PM2 module. ```bash pm2 uninstall ``` -------------------------------- ### Install PM2 Dependency Source: https://pm2.keymetrics.io/docs/usage/pm2-api Add PM2 as a project dependency using npm. ```bash npm install pm2 --save ``` -------------------------------- ### Act on Specific Applications in Configuration File Source: https://pm2.keymetrics.io/docs/usage/pm2-doc-single-page Use the '--only' option to manage specific applications defined in a configuration file. Multiple apps can be specified by comma separation. ```bash pm2 start ecosystem.config.js --only api-app ``` ```bash pm2 start ecosystem.config.js --only "api-app,worker-app" ``` -------------------------------- ### Add PM2 as yarn Dependency Source: https://pm2.keymetrics.io/docs/integrations/heroku Install PM2 as a project dependency using yarn. ```bash yarn add pm2 ``` -------------------------------- ### Add PM2 as npm Dependency Source: https://pm2.keymetrics.io/docs/integrations/heroku Install PM2 as a project dependency using npm. ```bash npm install pm2 ``` -------------------------------- ### Expose RPC Method 'hello' Source: https://pm2.keymetrics.io/docs/usage/process-actions Create a JavaScript application that exposes an RPC method named 'hello' using the tx2 module. The method replies with a JSON object. ```javascript const tx2 = require('tx2') tx2.action('hello', (reply) => { reply({ answer : 'world' }) }) setInterval(function() { // Keep application online }, 100) ``` -------------------------------- ### Deploy Application Source: https://pm2.keymetrics.io/docs/usage/deployment Command to deploy the latest version of the application to the configured production environment. ```bash $ pm2 deploy production ``` -------------------------------- ### Update PM2 Startup Script Source: https://pm2.keymetrics.io/docs/usage/pm2-doc-single-page Run these commands to update the PM2 startup script after upgrading your Node.js installation. ```bash $ pm2 unstartup $ pm2 startup ``` -------------------------------- ### Update PM2 Daemon Source: https://pm2.keymetrics.io/docs/usage/update-pm2 After installing the latest PM2 version, run this command to update the in-memory PM2 daemon. ```bash pm2 update ``` -------------------------------- ### Managing All Applications in an Ecosystem File Source: https://pm2.keymetrics.io/docs/usage/application-declaration Commands to manage all applications defined within an ecosystem configuration file. This allows for batch operations on your entire application set. ```bash # Start all applications pm2 start ecosystem.config.js # Stop all pm2 stop ecosystem.config.js # Restart all pm2 restart ecosystem.config.js # Reload all pm2 reload ecosystem.config.js # Delete all pm2 delete ecosystem.config.js ``` -------------------------------- ### Configuring min_uptime with different units Source: https://pm2.keymetrics.io/docs/usage/pm2-doc-single-page Shows how to configure the 'min_uptime' option using milliseconds, hours, minutes, or seconds. ```json "min_uptime": 3000 ``` ```json "min_uptime": "1h" ``` ```json "min_uptime": "5m" ``` ```json "min_uptime": "10s" ``` -------------------------------- ### Generate Ecosystem Configuration File Source: https://pm2.keymetrics.io/docs/usage/quick-start Create a default ecosystem configuration file (`ecosystem.config.js`) which allows managing multiple applications and their specific configurations from a single file. ```bash $ pm2 ecosystem ``` -------------------------------- ### Serve static files from a directory Source: https://pm2.keymetrics.io/docs/usage/expose Use this command to serve static files from a specified folder or the current directory. The default port is 8080. Options like `--name` or `--watch` can be used. ```bash pm2 serve ``` -------------------------------- ### Configure basic authentication in a process file Source: https://pm2.keymetrics.io/docs/usage/expose Enable basic authentication in a process file by setting `PM2_SERVE_BASIC_AUTH` to 'true' and providing `PM2_SERVE_BASIC_AUTH_USERNAME` and `PM2_SERVE_BASIC_AUTH_PASSWORD`. ```javascript module.exports = { script: "serve", env: { PM2_SERVE_PATH: '.', PM2_SERVE_PORT: 8080, PM2_SERVE_BASIC_AUTH: 'true', PM2_SERVE_BASIC_AUTH_USERNAME: 'example-login', PM2_SERVE_BASIC_AUTH_PASSWORD: 'example-password' } } ``` -------------------------------- ### Incorrectly Parsed Node Arguments Source: https://pm2.keymetrics.io/docs/usage/pm2-doc-single-page Illustrates an example of how Node arguments might be incorrectly parsed if quoting is not handled properly. ```json [ "port=3001", "sitename='first", "pm2", "app'" ] ``` -------------------------------- ### pm2-runtime helper usage Source: https://pm2.keymetrics.io/docs/usage/docker-pm2-nodejs Displays the help information for the pm2-runtime command, outlining its options and commands for managing Node.js applications. ```bash >>> pm2-runtime -h Usage: pm2-runtime app.js pm2-runtime is a drop-in replacement node.js binary with some interesting production features Options: -V, --version output the version number -i --instances launch [number] of processes automatically load-balanced. Increase overall performances and performance stability. --secret [key] [MONITORING] keymetrics secret key --public [key] [MONITORING] keymetrics public key --machine-name [name] [MONITORING] keymetrics machine name --raw raw log output --json output logs in json format --format output logs formatted like key=val --delay delay start of configuration file by --web [port] launch process web api on [port] (default to 9615) --only only act on one application of configuration --no-auto-exit do not exit if all processes are errored/stopped or 0 apps launched --env [name] inject env_[name] env variables in process config file --watch watch and restart application on file change --error error log file destination (default disabled) --output output log file destination (default disabled) -h, --help output usage information Commands: * start start an application or json ecosystem file ``` -------------------------------- ### Procfile for Elastic Beanstalk Source: https://pm2.keymetrics.io/docs/usage/pm2-doc-single-page Create a Procfile at the root of your source bundle to specify the command that starts your application on AWS Elastic Beanstalk. ```plaintext web: npm start ``` -------------------------------- ### PM2 CLI Options Mapping to JSON Source: https://pm2.keymetrics.io/docs/usage/pm2-doc-single-page Illustrates how CLI options like 'exec_mode' and 'max_restarts' correspond to their JSON configuration counterparts. ```bash exec_mode -> --execute-command max_restarts -> --max-restarts force -> --force ``` -------------------------------- ### SystemD Unit File Configuration for Network Dependency Source: https://pm2.keymetrics.io/docs/usage/startup This configuration snippet ensures that the PM2 service waits for the network to be online before starting. ```systemd [Unit] Wants=network-online.target After=network.target network-online.target [....] [Install] WantedBy=multi-user.target network-online.target ``` -------------------------------- ### Save Application List for Reboot Source: https://pm2.keymetrics.io/docs/usage/startup After starting your applications, use this command to save the current list so PM2 can automatically restore them after a reboot. ```bash pm2 save ``` -------------------------------- ### Serve a Single Page Application (SPA) Source: https://pm2.keymetrics.io/docs/usage/expose Enable SPA mode with the `--spa` option to automatically redirect all queries to `index.html`. This is useful for frontend frameworks. ```bash pm2 serve --spa ``` -------------------------------- ### Refresh PM2 Keymetrics Connection Source: https://pm2.keymetrics.io/docs/faq Stop and then start the PM2 Keymetrics link to refresh the connection. This can resolve intermittent connection issues. ```bash pm2 link stop ``` ```bash pm2 link start ``` -------------------------------- ### Show Application Metadata Source: https://pm2.keymetrics.io/docs/usage/process-management Display detailed metadata, including configuration and status, for a specific application. ```bash $ pm2 show api ``` -------------------------------- ### PM2 Error Example Source: https://pm2.keymetrics.io/docs/tutorials/capistrano-like-deployments Shows a common error message encountered when PM2 commands fail due to a deleted working directory. ```bash fatal: Unable to read current working directory: No such file or directory. ``` -------------------------------- ### Generate Startup Script Source: https://pm2.keymetrics.io/docs/usage/quick-start Generate and enable a system startup script that ensures PM2 and all its managed processes are automatically restarted upon server boot or reboot. ```bash $ pm2 startup ``` -------------------------------- ### Set Process Title with Environment Variable Source: https://pm2.keymetrics.io/docs/usage/pm2-doc-single-page Set the process title for a PM2-managed application by specifying the PROCESS_FILE environment variable when starting the application. ```bash PM2_HOME='.pm2' pm2 start echo.js --name="echo-node-1" ```