Linux – How to limit memory for a service managed by systemd

linuxsystemd

I am aware of ulimit and I know how to limit memory for a process that I explicitly start, or start using a script. But in this case I have a service that is managed and launched by systemd.

How can I limit its max memory and have it killed (or even better: prevent it from memory allocation (return NULL to malloc / realloc)) when it reaches the memory usage maximum?

Best Answer

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).