Limiting memory and CPU per user

I wanted to restrict resources for guest users in one of my servers. cgroups does it perfectly.

1. In Ubuntu 14.04 install cgroup-bin. I am going to install 16.04 server in my servers and I’ll rewrite this post accordingly.

2. Enable memory management; edit /etc/default/grub

GRUB_CMDLINE_LINUX="cgroup_enable=memory swapaccount=1"
$ sudo update-grub
$ sudo reboot

You should see this:

$ ls /sys/fs/cgroup/
cpu  cpuacct  devices  freezer  memory

In one of my machines, cgroup was not mounting after rebooting. I had to reboot the computer a couple of times until it mounted.

3.1. [16.04 UPDATE] When I installed Ubuntu 16.04 on my Acer C720p, cgroups didn’t work with the setup below. Instead, much simpler, but less sophisticated way of setting it up was to create an entry in /etc/rc.local:

# added this to /etc/rc.local to execute on boot
cgcreate -a myuser:myuser -g memory:memlimit
# limit RAM usage to 1.7GB to user memlimit
echo 1700000000 > /sys/fs/cgroup/memory/memlimit/memory.limit_in_bytes

3.2. [NOT WORKING ANYMORE] In theory, the way of permanently setting limits is by editing /etc/cgconfig.conf. In the example, the user is limited to 1G of RAM and 100/1024 CPU time. But this is not working for me in 16.04, so I’m using 3.1 above.

group memlimit {
    memory {
        memory.limit_in_bytes = "1G";
    cpu {

4. Edit /etc/cgrules.conf

myuser          memory           memlimit/

5. Reboot.

6. Run cgrulesengd:

sudo cgrulesengd

7. [NOT WORKING/NOT NECESSARY ANYMORE] If you change /etc/cgconfig.conf, update the configuration:

sudo cgconfigparser -l /etc/cgconfig.conf

8. [NOT SURE IF NECESSARY] Make this service start automatically:

sudo echo -e "/usr/sbin/cgrulesengd" > /etc/init.d/cgconfigparser
sudo update-rc.d cgrulesengd defaults

Because of the mount problem, I wasn’t able to start cgred, only after rebooting a couple of times memory control kicked in. Once I rebooted, I was able to edit /etc/cgconfig.conf with different memory limits and restart with service cgconfig.

Beware that swap will be used. I think it’s possible to control swap usage too, though, but probably you have to use LXC.



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s