6

Node.js can be used with Jemalloc (https://github.com/nodejs/node/issues/21973). In most cases it would shorten RSS and this is my huge problem.

But I can't find any info about how to use node with Jemalloc, nor on a machine, nor in docker.

Can anybody help with this?

Terion
  • 2,396
  • 3
  • 28
  • 42

1 Answers1

8

I just went through the process of switching our nodejs app to jemalloc, here is how I did it on Debian stretch:

Install jemalloc:

sudo apt-get install libjemalloc-dev

Find the jemalloc binary:

sudo find / -name "*jemalloc*"

Look for a file in a folder like /usr/lib/... ending with .so, for example path could be /usr/lib/x86_64-linux-gnu/libjemalloc.so

Configure server to use jemalloc for all programs:

  1. Create file with preloading config:

sudo nano /etc/ld.so.preload

  1. Add the path to the jemalloc binary to the file:

/path/to/jemalloc/binary

  1. Restart nodejs and check if jemalloc is used, e.g. like this (if jemalloc is used you should see some lines showing the jemalloc binary):

cat /proc/<PID OF NODEJS>/smaps | grep jemalloc

Alternative: Use jemalloc only for nodejs

In bash execute

export LD_PRELOAD=$LD_PRELOAD:/path/to/jemalloc/binary

before starting the nodejs process

Tyreal
  • 463
  • 3
  • 7
  • Thank you! I'll try soon. But does this mean that jemalloc will become a system-wide memory allocator? – Terion Nov 23 '18 at 15:34
  • Actually yes. In case you do not want that you could do: export LD_PRELOAD=$LD_PRELOAD: before starting the nodejs process. However this requires to do it each time before nodejs starts. There are probably options to only configure it for the nodejs binary but I am not aware of those right now... – Tyreal Nov 26 '18 at 09:48
  • On Amazon Linux 2 I'm getting : Error in munmap(): Invalid argument after starting a nodejs process – Vincent Jul 03 '22 at 19:19
  • Hi Vincent, could be the specific setup of OS on Amazon's Linux 2. The procedure is tested on Debian Stretch. In the meantime I have this running on a couple of Ubuntu 20.04 servers as well as some Debian Buster hosts. So I assume it should work for most not too old Debian derivatives. – Tyreal Jul 05 '22 at 06:54
  • Hi @Tyreal, do u mean the `/path/to/jemalloc/binary` in `export LD_PRELOAD=$LD_PRELOAD:/path/to/jemalloc/binary` to be something like `/usr/bin/jemalloc.sh` and not something like `/usr/lib64/libjemalloc.so`? – Son Nguyen Feb 21 '23 at 11:37
  • 1
    @SonNguyen no, it needs to be the file ending with `.so` which was installed by the apt repo. – Tyreal Feb 22 '23 at 12:08