Search code examples
node.jsubuntuforever

Node forever (npm package) memory leak on the server


I am using forever package to run my Node.js script. (not a web server). However, because of it, I have memory leak and even after stopping all processes, my memory is still taken:

root@aviok-cdc-elas-001:~# forever stopall
info:    No forever processes running
root@aviok-cdc-elas-001:~# forever list
info:    No forever processes running
root@aviok-cdc-elas-001:~# free -lm
             total       used       free     shared    buffers     cached
Mem:         11721       6900       4821          5        188       1242
Low:         11721       6900       4821
High:            0          0          0
-/+ buffers/cache:       5469       6252
Swap:            0          0          0

Also to mention, there is no memory leak from the script when ran locally without forever. I run it on Ubuntu server. And if I would reboot server now:

root@aviok-cdc-elas-001:~# reboot

Broadcast message from root@aviok-cdc-elas-001
        (/dev/pts/0) at 3:19 ...

The system is going down for reboot NOW!

My RAM would be free again:

root@aviok-cdc-elas-001:~# free -lm
             total       used       free     shared    buffers     cached
Mem:         11721       1259      10462          5         64        288
Low:         11721       1259      10462
High:            0          0          0
-/+ buffers/cache:        905      10816
Swap:            0          0          0

I also want to mention that, when my script finishes what it is doing (and it does eventually) I have db.close and process.exit calls to make sure everything is killed from the side of my script. However, even after that RAM is taken away. Now I am aware that forever will run that script again after it is killed. So my questions are:

  • How do I tell forever to not execute script again if it is finished?
  • How do I stop forever properly so it does NOT take any RAM after I stopped it?

The reason I am using forever package for this is because my script needs a lot of time to do what it does and my SSH session would end, and so would Node script which I ran in a regular way.


Solution

  • From what I can see, the RAM isn't taken away, or leaking, it's being used by Linux as file system cache (because unused RAM is wasted RAM).

    From the 6900 megs of "used" RAM, 5469 is used as buffer cache. Linux will reduce this amount automatically when processes request memory.

    If you want a long-running process to keep running after you log out (or after your SSH session gets killed), you have various options that don't require forever:

    • Background the process, making sure that any "logout" signals are ignored:

      $ nohup node script.js &
      
    • Use a terminal multiplexer like tmux or screen.