Moving from development to production requires more than just changing environment variables. Production-ready PM2 deployments demand robust process management, automatic startup on system boot, security hardening, and seamless integration with Linux system services. This comprehensive guide will transform your PM2 setup into an enterprise-grade production environment.
Understanding Systemd and PM2 Integration
Systemd is the init system used by modern Linux distributions, including Ubuntu. It manages system services, handles dependencies, and ensures services start automatically on boot. PM2’s systemd integration creates a bridge between your Node.js applications and the system’s service management.
graph TD A[System Boot] --> B[Systemd Init] B --> C[Load PM2 Service] C --> D[PM2 Daemon Start] D --> E[Load Ecosystem Config] E --> F[Start App Instance 1] E --> G[Start App Instance 2] E --> H[Start App Instance N] I[System Shutdown] --> J[Systemd Stop Services] J --> K[PM2 Graceful Shutdown] K --> L[Stop All App Instances]
PM2 Startup Generation Process
# Generate startup script for current user
pm2 startup
# Execute the generated command (example)
sudo env PATH=$PATH:/usr/bin /usr/lib/node_modules/pm2/bin/pm2 startup systemd -u $(whoami) --hp $HOME
# Verify the service was created
systemctl status pm2-$(whoami)
User Management and Security Hardening
Creating Dedicated PM2 User
# Create dedicated user for PM2 applications
sudo useradd -r -s /bin/bash -d /home/pm2user -m pm2user
# Set up proper directory structure
sudo mkdir -p /home/pm2user/{apps,logs,.pm2}
sudo chown -R pm2user:pm2user /home/pm2user
# Create application directory
sudo mkdir -p /var/www/myapp
sudo chown -R pm2user:pm2user /var/www/myapp
Auto-Startup Configuration
Complete Startup Setup Process
# Switch to PM2 user
sudo su - pm2user
# Start your applications
cd /var/www/myapp
pm2 start ecosystem.config.js --env production
pm2 save
# Exit back to sudo user
exit
# Generate startup script for pm2user
sudo pm2 startup systemd -u pm2user --hp /home/pm2user
# Enable the service
sudo systemctl enable pm2-pm2user
sudo systemctl start pm2-pm2user
flowchart TD A[System Boot] --> B{Network Ready?} B -->|Yes| D[Start Dependencies] B -->|No| C[Wait for Network] C --> B D --> E[MySQL Service] D --> F[Redis Service] E --> H[All Dependencies Ready] F --> H H --> I[Start PM2 Service] I --> J[Load Environment Variables] J --> K[Execute PM2 Resurrect] K --> L[Applications Running]
Service Monitoring and Management
Essential Systemctl Commands
# Check service status
sudo systemctl status pm2-pm2user
# Start/stop/restart service
sudo systemctl start pm2-pm2user
sudo systemctl stop pm2-pm2user
sudo systemctl restart pm2-pm2user
# View service logs
sudo journalctl -u pm2-pm2user -f
What’s Next?
You now have comprehensive knowledge of production-ready PM2 deployment with systemd integration. In the next part, we’ll explore advanced monitoring, logging, and alerting systems.