PM2内存占用过高、进程数持续增长,求服务器内存管控方案
Fixing High Memory Usage for Node.js/PM2 on Ubuntu 18.04
Hey there, let's work through your memory issue—8GB RAM nearly maxed out with 4 Node.js instances under PM2 4.4.1 is definitely not ideal. Here's a step-by-step plan to get your memory back in check:
1. First: Hunt Down Unnecessary Processes
Before tweaking configurations, let's make sure you're not running extra processes you don't need:
- Check PM2-managed instances: Run
pm2 listto see all apps PM2 is monitoring. Look for duplicate instances, apps marked aserrored/stoppedbut still consuming memory, or apps you no longer need. Delete them withpm2 delete <app-id-or-name>. - Find unmanaged Node processes: Use
ps aux | grep nodeto list all Node.js processes on your server. If you see any that aren't in thepm2 listoutput (like manually started instances), kill them safely withkill -9 <pid>—just double-check you're not deleting a critical process! - Spot memory leak clues: Dive into PM2 logs with
pm2 logsto look for repeated errors, infinite loops, or patterns where memory usage climbs steadily without dropping. These are red flags for code-level leaks.
2. Optimize PM2 to Cap Memory Usage
PM2 has built-in tools to prevent individual instances from hogging too much RAM:
- Add memory limits to your PM2 config: Create or edit your
ecosystem.config.jsfile to include a memory restart threshold. For your 8GB server, setting a 1GB limit per instance makes sense:module.exports = { apps : [{ name: "your-app", script: "./app.js", instances: 4, max_memory_restart: '1G', // Restart if instance exceeds 1GB RAM restart_delay: 1000 // Add a small delay to avoid thrashing }] } - Reload the config: Apply the changes with
pm2 reload ecosystem.config.js. This will restart your instances with the new memory limits. - Avoid over-scaling: While
-i maxspawns instances equal to your CPU cores (8 in your case), 4 instances should be sufficient unless your app is CPU-bound. Stick with 4 for now until you resolve the memory leak.
3. Diagnose and Fix Node.js Memory Leaks
Most excessive memory usage comes from code-level leaks. Here's how to track them down:
- Real-time monitoring: Launch
pm2 monitto get a live view of each instance's CPU and memory usage. Watch for instances that keep growing in memory without ever releasing it—those are your suspects. - Use Node.js debugging tools: For problematic instances, enable inspection by updating your ecosystem config to include
node_args: "--inspect", then runpm2 reload. Connect Chrome DevTools (viachrome://inspect) to the instance, go to the Memory tab, and take heap snapshots to identify unused variables, lingering timers, or unremoved event listeners. - Check common leak points: Look for:
- Global variables that accumulate data over time
- Unclear
setIntervaltimers or event listeners that aren't removed when no longer needed - Caches that lack size limits or expiration policies
4. System-Level Memory Cleanup (Quick Wins)
If you need immediate relief while fixing the root cause:
- Clear system cache: Run
sudo sync && sudo sysctl -w vm.drop_caches=3to free up page cache, directory entries, and inodes. This is a temporary fix but can give you breathing room. - Audit other services: Use
htopto see if other services (like databases, Nginx, or unused background processes) are eating into your RAM. Stop any unnecessary services withsudo systemctl stop <service-name>(and disable them on boot withsudo systemctl disable <service-name>if you don't need them).
5. Long-Term Monitoring and Maintenance
To prevent this from happening again:
- Update PM2: Your version (4.4.1) is a bit outdated—upgrade to the latest stable version with
npm install pm2@latest -gto get bug fixes and improved memory management. - Set up alerts: Use PM2's built-in alerting or tools like
monitto get notified when memory usage crosses a threshold (e.g., 70% of total RAM). - Regular log reviews: Schedule weekly checks of
pm2 logsto catch early signs of memory leaks or process issues.
内容的提问来源于stack exchange,提问作者agtabesh




