patternjavascriptModerate
PM2 process management: ecosystem config and zero-downtime reload
Viewed 0 times
pm2cluster modezero downtimereloadecosystem configprocess managernodejs
Problem
Running node server.js directly means the process dies on crash, doesn't restart on server reboot, and restarts cause brief downtime.
Solution
Use pm2 with an ecosystem config file:
// ecosystem.config.js
module.exports = {
apps: [{
name: 'myapp',
script: './dist/server.js',
instances: 'max', // Use all CPU cores
exec_mode: 'cluster', // Required for multiple instances
watch: false,
max_memory_restart: '1G',
env: {
NODE_ENV: 'development',
},
env_production: {
NODE_ENV: 'production',
PORT: 3000,
},
error_file: '/var/log/myapp/error.log',
out_file: '/var/log/myapp/out.log',
log_date_format: 'YYYY-MM-DD HH:mm:ss',
}]
};# Start / reload
pm2 start ecosystem.config.js --env production
pm2 reload myapp # Zero-downtime reload
pm2 save # Save process list
pm2 startup # Generate startup scriptWhy
Cluster mode distributes connections across worker processes. pm2 reload performs rolling restarts — one worker at a time — so there is no downtime during deploys.
Gotchas
- cluster mode requires your app to be stateless — in-memory sessions or WebSocket state breaks with multiple workers
- pm2 save must be run after any config change to persist across reboots
- pm2 startup generates a command you must run as root — read its output carefully
- pm2 logs buffers output — use pm2 flush periodically to prevent the log buffer from growing too large
Revisions (0)
No revisions yet.