πŸ“š 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)

  1. Initial Server Setup & User Configuration

    • System updates, non-root user creation, timezone configuration
  2. SSH Hardening & Key Management

    • SSH key generation (RSA/ED25519), key deployment, advanced SSH configuration
  3. Firewall & Network Security

    • UFW setup, Fail2ban configuration, rate limiting, DDoS protection, port knocking
  4. Kernel Hardening & System Security

    • sysctl hardening, IPv6 disabling, /tmp security, ASLR, core dump restriction

Advanced Security (Sections 5-7)

  1. Mandatory Access Control (AppArmor)

    • AppArmor installation, custom Node.js/PM2 profiles, profile management
  2. System Auditing (Auditd)

    • Comprehensive audit rules, log analysis, automated reports
  3. Intrusion Detection & File Integrity

    • AIDE setup, rkhunter configuration, ClamAV antivirus, automated scans

Monitoring & Application (Sections 8-11)

  1. System Monitoring & Performance Tools

    • htop, iotop, nethogs, sysstat, netdata, Prometheus node_exporter
  2. Node.js & PM2 Installation

    • NVM/NodeSource installation, PM2 setup, startup scripts, pm2-logrotate
  3. Advanced PM2 Configuration

    • Ecosystem files, cluster mode, memory leak detection, TypeScript support, deployment system
  4. Custom PM2 & Node.js Monitoring

    • PM2 monitoring scripts, heap monitoring, event loop lag detection, alerting integration

Infrastructure Services (Sections 12-14)

  1. Log Management & Analysis

    • Logwatch, PM2 logs, rsyslog centralization, log rotation, ELK stack basics
  2. Nginx Reverse Proxy (Advanced)

    • Load balancing, WebSocket support, security headers, rate limiting, GeoIP blocking, caching, ModSecurity WAF
  3. 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)

  1. Process Monitoring & Auto-Recovery

    • Monit installation, service monitoring, email/webhook alerts, web interface
  2. 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)

  1. Automated Backup Strategy

    • Full system backups, S3 integration, remote sync, disaster recovery procedures
  2. 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

  1. Deployment Automation - Git workflows, CI/CD integration, zero-downtime deployments
  2. High Availability Setup - Clustering, load balancing, failover strategies
  3. Performance Optimization - Node.js tuning, V8 optimization, kernel parameters
  4. Security Scanning & Hardening - Lynis, OpenVAS, npm audit, Snyk integration
  5. Compliance & Logging - GDPR, PCI-DSS, SOC 2 requirements, audit trails
  6. Maintenance & Operations - Checklists, procedures, capacity planning
  7. Advanced Troubleshooting - strace, lsof, tcpdump, perf, debugging techniques
  8. 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)

  1. Section 1: Initial Server Setup
  2. Section 2: SSH Hardening
  3. Section 3: Firewall & Fail2ban
  4. Section 4: Kernel Hardening

Phase 2: Application Stack (1-2 hours)

  1. Section 9: Node.js & PM2 Installation
  2. Section 10: PM2 Configuration
  3. Section 13: Nginx Reverse Proxy
  4. Section 14: SSL Certificates

Phase 3: Monitoring (1 hour)

  1. Section 11: PM2 Monitoring
  2. Section 12: Log Management
  3. Section 15: Process Monitoring (Monit)

Phase 4: Reliability (1-2 hours)

  1. Section 17: Automated Backups
  2. 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

  1. Always test in staging first before applying to production
  2. Keep backups off-site and test restore procedures regularly
  3. Monitor security logs daily for unusual activity
  4. Update regularly but during maintenance windows
  5. Document changes to configuration for team knowledge
  6. Use version control for configuration files
  7. Implement gradual rollouts for application updates
  8. Have rollback procedures documented and tested
  9. Review access logs and remove unused accounts
  10. Conduct security audits quarterly with Lynis

πŸ“ž Getting Help

Troubleshooting

  1. Check the specific section’s troubleshooting notes
  2. Review system logs: /var/log/syslog and /var/log/auth.log
  3. Check PM2 logs: pm2 logs
  4. Verify service status: sudo systemctl status <service>
  5. Test configuration: sudo nginx -t, pm2 list

Common Issues

  • PM2 not starting on boot: Check pm2 startup configuration
  • 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

  1. Provision server
  2. Complete Phases 1-3 from Quick Start
  3. Deploy application code
  4. Test all services
  5. Configure monitoring and alerts
  6. Document configuration

Application Updates

  1. Test in staging environment
  2. Create backup before deployment
  3. Deploy using pm2 reload for zero-downtime
  4. Monitor logs for errors
  5. Verify health check endpoints
  6. Rollback if issues detected

System Updates

  1. Schedule during maintenance window
  2. Notify team of update schedule
  3. Create full system backup
  4. Apply updates: sudo apt update && sudo apt upgrade
  5. Restart services if required
  6. Verify all services operational
  7. 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