Skip to content

Instantly share code, notes, and snippets.

@AliKhadivi
Last active August 10, 2023 08:46
Show Gist options
  • Save AliKhadivi/bd1fa0fee51a06841f03961b5945f3cf to your computer and use it in GitHub Desktop.
Save AliKhadivi/bd1fa0fee51a06841f03961b5945f3cf to your computer and use it in GitHub Desktop.

Install and config cgroup with cgroupfs in Ubuntu

Install

Install required packages

apt update && apt install cgroup-tools cgroup-lite libcgroup1  cgroupfs-mount

Configure

copy cgred.conf from examples

cp /usr/share/doc/cgroup-tools/examples/cgred.conf /etc/

/etc/cgconfig.conf

group web2 {
     cpu {
         cpu.cfs_quota_us=10000;
     }
     memory {
         memory.limit_in_bytes = 1024m;
     }
}

cpu.cfs_quota_us = 10000 equals to 10% cpu usage memory.limit_in_bytes = 1024 equals to 1G of system memory

/etc/cgrules.conf

#<user>    <controllers>           <destination>
web2       cpu,memory              web2

This will limit every process of the user web2 to 10% CPU and 1G of memory.

For testing use this commands:

/usr/sbin/cgconfigparser -l /etc/cgconfig.conf
/usr/sbin/cgrulesengd -vvv

check if cgroup’s are working properly

cat /sys/fs/cgroup/cpu/web2/tasks
cat /sys/fs/cgroup/memory/web2/tasks

Create Service

Here my systemd service files, install them the usual systemd way

‍‍cgconfigparser.service

[Unit]
Description=cgroup config parser
After=network.target
[Service]
User=root
Group=root
ExecStart=/usr/sbin/cgconfigparser -l /etc/cgconfig.conf
Type=oneshot
[Install]
WantedBy=multi-user.target

cgrulesgend.service

[Unit]
Description=cgroup rules generator
After=network.target cgconfigparser.service
[Service]
User=root
Group=root
Type=forking
EnvironmentFile=-/etc/cgred.conf
ExecStart=/usr/sbin/cgrulesengd
Restart=on-failure
[Install]
WantedBy=multi-user.target

reload systemd and start services

systemctl daemon-reload
systemctl enable cgconfigparser
systemctl enable cgrulesgend
systemctl start cgconfigparser
systemctl start cgrulesgend

Have fun!

Source: paranoids.at

group web2 {
cpu {
cpu.cfs_quota_us=10000;
}
memory {
memory.limit_in_bytes = 1024m;
}
}
#<user> <controllers> <destination>
web2 cpu,memory web2
[Unit]
Description=cgroup rules generator
After=network.target cgconfigparser.service
[Service]
User=root
Group=root
Type=forking
EnvironmentFile=-/etc/cgred.conf
ExecStart=/usr/sbin/cgrulesengd
Restart=on-failure
[Install]
WantedBy=multi-user.target
[Unit]
Description=cgroup config parser
After=network.target
[Service]
User=root
Group=root
ExecStart=/usr/sbin/cgconfigparser -l /etc/cgconfig.conf
Type=oneshot
[Install]
WantedBy=multi-user.target
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment