Topic 55 of 55
PM2 Ecosystem
Overview
Typing out `pm2 start app.js --name api --env production` every time is tedious. PM2 allows you to define an `ecosystem.config.js` file to declare your app's environment variables, scaling options, and configuration as code.
Syntax
javascript
// Generate a template by running: pm2 init
// ecosystem.config.js
module.exports = {
apps: [{
name: "my-web-api",
script: "./server.js",
instances: "max", // Cluster mode: spawn as many as CPU cores
exec_mode: "cluster", // Run in cluster mode
watch: false, // Don't restart on file changes in production
env: {
NODE_ENV: "development",
PORT: 3000
},
env_production: {
NODE_ENV: "production",
PORT: 8080,
DB_HOST: "prod.database.com"
}
}]
};
// Start the app using the production environment block:
// pm2 start ecosystem.config.js --env productionCommon Pitfalls
- When running `pm2 start` with an ecosystem file, changes to the file aren't picked up automatically. You must run `pm2 restart ecosystem.config.js --update-env` to apply changes.
Real-World Example
Defining multiple microservices in a single ecosystem file:
example
javascript
module.exports = {
apps: [
{
name: "main-api",
script: "./api/index.js",
instances: 2,
},
{
name: "worker-queue",
script: "./worker/jobProcessor.js",
instances: 1, // Only want 1 worker processing jobs to avoid race conditions
},
{
name: "frontend-server",
script: "npm",
args: "run start", // You can run npm scripts via PM2!
}
]
};
// Running 'pm2 start' will launch all 3 apps simultaneously.