PM2 常见命令
shell
# config
pm2 ecosystem # create a configuration file
pm2 start ecosystem.config.js
# Restart application on changes
pm2 start env.js --watch --ignore-watch="node_modules"
# Fork mode
pm2 start app.js --name my-api # Name process
# Cluster mode
pm2 start app.js -i 0 # Will start maximum processes with LB depending on available CPUs
pm2 start app.js -i max # Same as above, but deprecated.
pm2 scale app +3 # Scales `app` up by 3 workers
pm2 scale app 2 # Scales `app` up or down to 2 workers total
# Listing
pm2 list # Display all processes status
pm2 jlist # Print process list in raw JSON
pm2 prettylist # Print process list in beautified JSON
pm2 describe 0 # Display all information about a specific process
pm2 monit # Monitor all processes
# Logs
pm2 logs [--raw] # Display all processes logs in streaming
pm2 flush # Empty all log files
pm2 reloadLogs # Reload all logs
# Actions
pm2 stop all # Stop all processes
pm2 restart all # Restart all processes
pm2 reload all # Will 0s downtime reload (for NETWORKED apps)
pm2 stop 0 # Stop specific process id
pm2 restart 0 # Restart specific process id
pm2 delete 0 # Will remove process from pm2 list
pm2 delete all # Will remove all processes from pm2 list
# Misc
pm2 reset <process> # Reset meta data (restarted time...)
pm2 updatePM2 # Update in memory pm2
pm2 ping # Ensure pm2 daemon has been launched
pm2 sendSignal SIGUSR2 my-app # Send system signal to script
pm2 start app.js --no-daemon
pm2 start app.js --no-vizion
pm2 start app.js --no-autorestartcli
shell
# cli
$ pm2 start bashscript.sh
$ pm2 start python-app.py --watch
$ pm2 start binary-file -- --port 1520
# Specify an app name
--name <app_name>
# Watch and Restart app when files change
--watch
# Set memory threshold for app reload
--max-memory-restart <200MB>
# Specify log file
--log <log_path>
# Pass extra arguments to the script
-- arg1 arg2 arg3
# Delay between automatic restarts
--restart-delay <delay in ms>
# Prefix logs with time
--time
# Do not auto restart app
--no-autorestart
# Specify cron for forced restart
--cron <cron_pattern>
# Attach to application log
--no-daemonNode Cluster
javascript
const cluster = require('node:cluster')
const express = require('views/node/express')
if (cluster.isMaster) {
// 下面调用了2次cluster.fork函数,意味着当我们在终端执行node index.js时,还会再额外执行2次index.js,
// 只不过另外2次的cluster.isMaster设置为false
cluster.fork()
cluster.fork()
} else {
const app = express()
const doWork = (duration) => {
const start = Date.now()
while (Date.now() - start < duration) {}
}
app.get('/', (req, res) => {
doWork(5000)
res.send('Hi there')
})
app.get('/fast', (req, res) => {
console.log('fast')
res.send('This was fast!')
})
app.listen(3000)
}
// 代码中的 cluster.fork() 被调用了两次,这会创建两个子进程。当这两个子进程开始运行时,它们会共享同一个端口(3000)并监听相同的路由。
// 当一个请求进入主进程并匹配到 /fast 路由时,会触发对应的回调函数,打印出 "fast" 并发送响应。由于只有一个主进程在接收请求,因此 "fast" 只会被打印一次。
// 同一台机器创建多个主进程是没有意义的,因为共享计算资源;多个应用程序实例通常在不同的机器上运行,以实现负载均衡和高可用性