How to limit memory for a service managed by systemd

The manpage for systemd.exec has a list of LimitXXXX instructions and a handy table comparing them to the ulimit options, by way of the setrlimit() system call.

To limit the process's entire address space (ulimit -v) use LimitAS=. Otherwise to limit the just the stack (ulimit -s) use LimitSTACK= or data segment (ulimit -d) use LimitDATA=

According to the setrlimit() manpage, these limits will cause allocating additional memory to fail. STACK and AS will terminate the program with a sigsegv if the limit is reached and the stack needs to grow (and the program did not handle this).


Systemd supports limiting memory usage via the MemoryLimit option, as described at: https://www.freedesktop.org/software/systemd/man/systemd.resource-control.html

The way system handles the situation when maximum memory allowed (per service) is exhausted depends on both the underlying cgroups implementation and the way systemd implements resource control; I'm guessing the process would be killed (via OOM killer).


For limits analogous to ulimit:

man systemd.exec

...
LimitAS=(like ulimit -v)
...
LimitRSS=(like ulimit -m)
...