Examples
Practical code examples and use cases
Learn how to use PM2Stack with real-world examples and code samples.
Code Examples
Basic Usage
A simple example showing how to create a PM2Stack instance and register a single application.
import { PM2Stack, PM2App } from 'pm2-stack';
// Create a PM2Stack instance
const stack = new PM2Stack({
verbose: true,
exitOnStart: false
});
// Create a simple web server app
const webApp = new PM2App({
id: 'web-server',
entryPoint: './server.js',
instances: 1,
env: {
PORT: '3000',
NODE_ENV: 'production'
}
});
// Register and start the app
stack.registerApp(webApp);
await stack.start();
console.log('✅ Web server started on port 3000');
Cluster Mode
Run multiple instances of your application in cluster mode for better performance and load distribution.
import { PM2Stack, PM2App } from 'pm2-stack';
const stack = new PM2Stack({ verbose: true });
// Create a cluster of web servers
const webApp = new PM2App({
id: 'web-server',
entryPoint: './server.js',
instances: 4, // 4 instances in cluster mode
env: {
PORT: '3000',
NODE_ENV: 'production'
}
});
stack.registerApp(webApp);
await stack.start();
console.log('✅ 4 web server instances started in cluster mode');
💡 Note
When instances > 1, PM2 automatically uses cluster mode.
Each instance will run on a separate CPU core for optimal performance.
Environment Variables
Pass environment variables to your applications for configuration and secrets management.
import { PM2Stack, PM2App } from 'pm2-stack';
const stack = new PM2Stack({ verbose: true });
// API server with environment variables
const apiApp = new PM2App({
id: 'api-server',
entryPoint: './api.js',
instances: 2,
env: {
NODE_ENV: 'production',
PORT: '3001',
API_KEY: 'your-secret-key-here',
DATABASE_URL: 'postgres://localhost:5432/mydb',
REDIS_URL: 'redis://localhost:6379',
JWT_SECRET: 'your-jwt-secret',
LOG_LEVEL: 'info'
}
});
stack.registerApp(apiApp);
await stack.start();
console.log('✅ API server started with environment variables');
🔒 Security Tip
For production, use environment variable files or secret management systems instead of hardcoding sensitive values.
Multiple Applications
Manage multiple applications with different configurations in a single PM2Stack instance.
import { PM2Stack, PM2App } from 'pm2-stack';
const stack = new PM2Stack({
verbose: true,
exitOnStart: false
});
// Web server (cluster mode)
const webApp = new PM2App({
id: 'web-server',
entryPoint: './web-server.js',
instances: 3,
env: {
PORT: '3000',
NODE_ENV: 'production'
}
});
// API server (single instance)
const apiApp = new PM2App({
id: 'api-server',
entryPoint: './api-server.js',
instances: 1,
env: {
PORT: '3001',
NODE_ENV: 'production',
API_KEY: 'secret-key'
}
});
// Worker service (background processing)
const workerApp = new PM2App({
id: 'worker-service',
entryPoint: './worker.js',
instances: 2,
env: {
NODE_ENV: 'production',
QUEUE_URL: 'redis://localhost:6379'
}
});
// Register all apps
stack.registerApp(webApp);
stack.registerApp(apiApp);
stack.registerApp(workerApp);
// Start everything
await stack.start();
console.log('✅ All applications started successfully');
Error Handling
Implement proper error handling for production applications.
import { PM2Stack, PM2App } from 'pm2-stack';
async function startApplication() {
const stack = new PM2Stack({
verbose: true,
exitOnStart: false
});
try {
// Create and register apps
const webApp = new PM2App({
id: 'web-server',
entryPoint: './server.js',
instances: 2,
env: { PORT: '3000' }
});
stack.registerApp(webApp);
// Start the stack
await stack.start();
console.log('✅ Application started successfully');
// Handle graceful shutdown
process.on('SIGINT', async () => {
console.log('🛑 Shutting down gracefully...');
await stack.stop();
});
process.on('SIGTERM', async () => {
console.log('🛑 Shutting down gracefully...');
await stack.stop();
});
} catch (error) {
console.error('❌ Failed to start application:', error.message);
process.exit(1);
}
}
// Start the application
startApplication();
⚠️ Important
Always implement graceful shutdown handlers to ensure your applications stop cleanly when receiving termination signals.
Running the Examples
To run the examples in this project:
# Install dependencies
npm install
# Build the library
npm run build
# Run the basic example
node examples/basic-example.js
# Or run the TypeScript example
npx ts-node examples/basic-example.ts
Check the examples/ directory for more complete examples with sample applications.