Better Memory Performance in Ruby/Rails with Jemalloc

jemalloc is a general purpose malloc(3) implementation that emphasizes fragmentation avoidance and scalable concurrency support. It really shines when used with ruby, and adding it is pretty painless.

All you have to do is add the following 2 lines to your Dockerfile.

RUN apt-get update ; \
    apt-get install -y --no-install-recommends libjemalloc2 ;

ENV LD_PRELOAD=/usr/lib/x86_64-linux-gnu/

We are going to use the LD_PRELOAD environment variable approach above. If you set LD_PRELOAD to the path of a shared object, that file will be loaded before any other library (including the C runtime, So to run our jemalloc implementation, we just define the path of the jemalloc lib.

For M1 Macs you will need to change the path as follows:

# use this for m1 macs
ENV LD_PRELOAD=/usr/lib/aarch64-linux-gnu/