AbstractBrain Answers About us

How to enable jemalloc for Ruby docker image

Question

How can you enable jemalloc for a Rails app running in the Ruby docker image?

In order to reduce the memory usage and to align with Rails 7.2 defaults, we would like to use jemalloc for an existing Rails application that already has its own Dockerfile.

Answer

First you need to install jemalloc by adding the following command to the Dockerfile:

FROM ruby:3.3.4

RUN apt-get update && apt-get install -y libjemalloc2

Then you need to set this env variable (directly in the Dockerfile or at run time in Kubernetes or similar):

LD_PRELOAD=libjemalloc.so.2

This env variable works for most platforms and you don’t need to specify an absolute path to the library.

Finally you can verify if you have enabled jemalloc successfully. Open a shell in your container and run this command:

MALLOC_CONF=stats_print:true ruby -e "exit"

If there is no output it means that jemalloc is not installed properly, otherwise you will get some stats:

___ Begin jemalloc statistics ___
...