Limit Linux Resources – How to Restrict CPU and RAM Usage per User

linuxrate-limiting

I would like to limit CPU and ram usage per user.

So, let's say there is user john.
He can run as many processes as he wants, but he also needs to have 2048 megabytes of ram and 2 CPU cores.

I know there are methods like 'ulimit' and 'nice', but I'm limited to just one command, so I would need something like this:

limiter_cmd -ram 2048 -cpu 2 screen -s 1 ./script

Also, I'm using the 'screen' command to save sessions.

Best Answer

cgroups. On a systemd system, this implies altering resource controls on the user slices.

For systemd v239 and later, this can be set as the default limit via the dropin search truncation feature.

# mkdir -p /etc/systemd/system/user-.slice.d
# cat > /etc/systemd/system/user-.slice.d/50-memory.conf << EOF
[Slice]
MemoryMax=2G
CPUQuota=200%
EOF
# systemctl daemon-reload

You may need to enable CPU and memory accounting if it is not already, see man systemd.resource-control