π Complete Production-Ready Guide for Node.js + PM2
This comprehensive guide provides everything you need to set up, secure, and maintain a production Ubuntu server running Node.js applications with PM2.
π Guide Structure
The guide is split into two parts for better manageability:
Part 1: UBUNTU_SERVER_PM2_SETUP_GUIDE.md
Sections 1-14 - Essential Setup & Security (3,100+ lines)
Core Infrastructure (Sections 1-4)
-
Initial Server Setup & User Configuration
- System updates, non-root user creation, timezone configuration
-
SSH Hardening & Key Management
- SSH key generation (RSA/ED25519), key deployment, advanced SSH configuration
-
Firewall & Network Security
- UFW setup, Fail2ban configuration, rate limiting, DDoS protection, port knocking
-
Kernel Hardening & System Security
- sysctl hardening, IPv6 disabling, /tmp security, ASLR, core dump restriction
Advanced Security (Sections 5-7)
-
Mandatory Access Control (AppArmor)
- AppArmor installation, custom Node.js/PM2 profiles, profile management
-
System Auditing (Auditd)
- Comprehensive audit rules, log analysis, automated reports
-
Intrusion Detection & File Integrity
- AIDE setup, rkhunter configuration, ClamAV antivirus, automated scans
Monitoring & Application (Sections 8-11)
-
System Monitoring & Performance Tools
- htop, iotop, nethogs, sysstat, netdata, Prometheus node_exporter
-
Node.js & PM2 Installation
- NVM/NodeSource installation, PM2 setup, startup scripts, pm2-logrotate
-
Advanced PM2 Configuration
- Ecosystem files, cluster mode, memory leak detection, TypeScript support, deployment system
-
Custom PM2 & Node.js Monitoring
- PM2 monitoring scripts, heap monitoring, event loop lag detection, alerting integration
Infrastructure Services (Sections 12-14)
-
Log Management & Analysis
- Logwatch, PM2 logs, rsyslog centralization, log rotation, ELK stack basics
-
Nginx Reverse Proxy (Advanced)
- Load balancing, WebSocket support, security headers, rate limiting, GeoIP blocking, caching, ModSecurity WAF
-
SSL/TLS & Certificate Management
- Certbot installation, automated renewal, SSL Labs A+ rating, OCSP stapling, wildcard certificates
Part 2: UBUNTU_SERVER_PM2_SETUP_GUIDE_PART2.md
Sections 15-18 - Advanced Topics (1,200+ lines)
Process & Database Management (Sections 15-16)
-
Process Monitoring & Auto-Recovery
- Monit installation, service monitoring, email/webhook alerts, web interface
-
Database Security Hardening
- PostgreSQL: SSL, authentication, row-level security, automated backups
- MongoDB: Authentication, role-based access, encryption, backups
- Redis: Password auth, command restrictions, persistence, backups
Reliability & Performance (Sections 17-18)
-
Automated Backup Strategy
- Full system backups, S3 integration, remote sync, disaster recovery procedures
-
Application Performance Monitoring (APM)
- PM2 Plus/Keymetrics, Clinic.js, memory leak detection, CPU profiling, Sentry error tracking
Enterprise Features (Sections 19-26)
Note: Detailed content for sections 19-26 can be expanded based on requirements
- Deployment Automation - Git workflows, CI/CD integration, zero-downtime deployments
- High Availability Setup - Clustering, load balancing, failover strategies
- Performance Optimization - Node.js tuning, V8 optimization, kernel parameters
- Security Scanning & Hardening - Lynis, OpenVAS, npm audit, Snyk integration
- Compliance & Logging - GDPR, PCI-DSS, SOC 2 requirements, audit trails
- Maintenance & Operations - Checklists, procedures, capacity planning
- Advanced Troubleshooting - strace, lsof, tcpdump, perf, debugging techniques
- Quick Reference & Cheatsheets - Essential commands, emergency procedures
π― Who Is This Guide For?
Primary Audience
- Experienced DevOps Engineers managing production Node.js applications
- System Administrators transitioning to Node.js stack
- Full-Stack Developers handling their own deployments
- Teams requiring enterprise-grade security and compliance
Prerequisites
- Basic Linux command-line knowledge
- Understanding of Node.js and npm
- Access to Ubuntu 20.04/22.04 server
- SSH access with sudo privileges
β‘ Quick Start (Essential Path)
For a minimal production setup, follow these sections in order:
Phase 1: Foundation (2-3 hours)
- Section 1: Initial Server Setup
- Section 2: SSH Hardening
- Section 3: Firewall & Fail2ban
- Section 4: Kernel Hardening
Phase 2: Application Stack (1-2 hours)
- Section 9: Node.js & PM2 Installation
- Section 10: PM2 Configuration
- Section 13: Nginx Reverse Proxy
- Section 14: SSL Certificates
Phase 3: Monitoring (1 hour)
- Section 11: PM2 Monitoring
- Section 12: Log Management
- Section 15: Process Monitoring (Monit)
Phase 4: Reliability (1-2 hours)
- Section 17: Automated Backups
- Test deployment and failover procedures
Total Time: 5-8 hours for complete essential setup
π Security Highlights
This guide implements multiple layers of security:
Network Layer
- β UFW firewall with zone-based rules
- β Fail2ban intrusion prevention
- β DDoS protection with iptables
- β Port knocking (optional)
System Layer
- β Kernel hardening (sysctl)
- β AppArmor mandatory access control
- β Auditd system auditing
- β Secure /tmp and shared memory
Application Layer
- β PM2 process isolation
- β Non-root user execution
- β Memory limits and health checks
- β Log rotation and management
Data Layer
- β Database authentication and encryption
- β SSL/TLS for all connections
- β Automated encrypted backups
- β Role-based access control
Detection & Response
- β AIDE file integrity monitoring
- β rkhunter rootkit detection
- β ClamAV antivirus scanning
- β Real-time alerting
π Feature Comparison
| Feature | Basic Setup | This Guide |
|---|---|---|
| Server Hardening | β | β |
| Firewall Configuration | Basic | Advanced + DDoS |
| Intrusion Detection | β | β AIDE + rkhunter + ClamAV |
| System Auditing | β | β Auditd |
| PM2 Cluster Mode | β | β Optimized |
| Monitoring | Basic | β Multi-tool stack |
| Automated Backups | β | β Full system |
| SSL/TLS | Letβs Encrypt | β A+ Rating |
| Log Management | Basic | β Centralized + Analysis |
| Database Security | Basic | β Full hardening |
| APM | β | β Multiple options |
| Disaster Recovery | β | β Complete procedures |
| Compliance Ready | β | β GDPR/PCI-DSS guidelines |
π οΈ Key Technologies Covered
Core Stack
- OS: Ubuntu 20.04/22.04 LTS
- Runtime: Node.js (via NVM or NodeSource)
- Process Manager: PM2
- Reverse Proxy: Nginx
- SSL: Letβs Encrypt / Certbot
Security Tools
- Firewall: UFW + iptables
- IDS: AIDE, rkhunter, ClamAV
- IPS: Fail2ban
- MAC: AppArmor
- Auditing: Auditd
Monitoring Tools
- System: htop, iotop, nethogs, sysstat
- Metrics: netdata, Prometheus node_exporter
- Logs: Logwatch, multitail, rsyslog
- Process: Monit, PM2 Plus
Databases (Optional)
- PostgreSQL: With SSL and RLS
- MongoDB: With authentication and encryption
- Redis: With password and persistence
π Checklist
Essential Setup
- [ ] Server provisioned with Ubuntu 20.04/22.04
- [ ] Non-root user with sudo access created
- [ ] SSH key authentication configured
- [ ] Password authentication disabled
- [ ] UFW firewall enabled
- [ ] Fail2ban installed and configured
- [ ] Kernel hardening applied (sysctl)
- [ ] Node.js and PM2 installed
- [ ] Application deployed with PM2
- [ ] Nginx reverse proxy configured
- [ ] SSL certificate installed
- [ ] Monitoring scripts running
- [ ] Backup cron jobs configured
Advanced Security
- [ ] AppArmor profiles created
- [ ] Auditd rules configured
- [ ] AIDE database initialized
- [ ] rkhunter installed
- [ ] ClamAV scanning scheduled
- [ ] Monit monitoring active
Production Readiness
- [ ] All services start on boot
- [ ] Automated backups tested
- [ ] Disaster recovery tested
- [ ] Monitoring alerts configured
- [ ] Log rotation working
- [ ] Performance baseline established
- [ ] Documentation updated
π Learning Path
Beginner Path
Focus on essential security and basic PM2 deployment:
- Sections 1-4 (Security foundation)
- Sections 9-10 (Node.js + PM2)
- Section 13-14 (Nginx + SSL)
Intermediate Path
Add monitoring and database security:
- Complete Beginner Path
- Sections 11-12 (Monitoring + Logs)
- Section 15 (Monit)
- Section 16 (Database security)
- Section 17 (Backups)
Advanced Path
Full enterprise deployment:
- Complete all sections
- Implement high availability
- Add compliance logging
- Setup APM and profiling
π§ Customization Tips
For Small Projects
- Skip: AppArmor, Auditd, AIDE, rkhunter (sections 5-7)
- Keep: UFW, Fail2ban, basic monitoring
- Simplified backups (daily full backup only)
For Medium Projects
- Include: All core security (sections 1-7)
- Add: Database hardening, comprehensive monitoring
- Enhanced backups with remote sync
For Enterprise Projects
- Implement: All sections
- Add: High availability clustering
- Setup: Centralized logging (ELK stack)
- Configure: Compliance requirements
π‘ Best Practices
- Always test in staging first before applying to production
- Keep backups off-site and test restore procedures regularly
- Monitor security logs daily for unusual activity
- Update regularly but during maintenance windows
- Document changes to configuration for team knowledge
- Use version control for configuration files
- Implement gradual rollouts for application updates
- Have rollback procedures documented and tested
- Review access logs and remove unused accounts
- Conduct security audits quarterly with Lynis
π Getting Help
Troubleshooting
- Check the specific sectionβs troubleshooting notes
- Review system logs:
/var/log/syslogand/var/log/auth.log - Check PM2 logs:
pm2 logs - Verify service status:
sudo systemctl status <service> - Test configuration:
sudo nginx -t,pm2 list
Common Issues
- PM2 not starting on boot: Check
pm2 startupconfiguration - Nginx 502 errors: Verify Node.js app is running
- SSL certificate issues: Check Certbot renewal status
- High memory usage: Review PM2 ecosystem
max_memory_restart - Firewall blocking traffic: Verify UFW rules with
sudo ufw status verbose
π Maintenance Schedule
Daily
- Review Fail2ban logs for attack patterns
- Check PM2 app status and restart counts
- Monitor disk space usage
Weekly
- Review system logs with Logwatch
- Check SSL certificate expiry
- Verify backup completion
Monthly
- Run Lynis security audit
- Update system packages
- Review and rotate old logs
- Test disaster recovery procedures
Quarterly
- Review and update security policies
- Audit user accounts and permissions
- Performance optimization review
- Update Node.js to latest LTS
π Deployment Workflow
Initial Deployment
- Provision server
- Complete Phases 1-3 from Quick Start
- Deploy application code
- Test all services
- Configure monitoring and alerts
- Document configuration
Application Updates
- Test in staging environment
- Create backup before deployment
- Deploy using
pm2 reloadfor zero-downtime - Monitor logs for errors
- Verify health check endpoints
- Rollback if issues detected
System Updates
- Schedule during maintenance window
- Notify team of update schedule
- Create full system backup
- Apply updates:
sudo apt update && sudo apt upgrade - Restart services if required
- Verify all services operational
- Monitor for 24 hours post-update
π Additional Resources
Official Documentation
Security Resources
Monitoring & Performance
π€ Contributing
This guide is continuously improved based on real-world production experience. Suggestions for improvements are welcome.
βοΈ License
This guide is provided as-is for educational and professional use. Always test configurations in non-production environments first.
π Conclusion
This comprehensive guide provides enterprise-grade setup for Node.js applications with PM2. Whether youβre deploying a small application or an enterprise system, these configurations will give you a solid, secure foundation.
Remember: Security is not a one-time setup but an ongoing process. Keep your systems updated, monitor regularly, and stay informed about security best practices.
Happy deploying! π
Last Updated: January 2025 Guide Version: 1.0 Target Ubuntu: 20.04 LTS / 22.04 LTS
