How to Create a cgroup on CentOS 7

Introduction

Control Groups (cgroups) are a Linux kernel feature that allows you to allocate resources—such as CPU time, memory, and I/O bandwidth—among user-defined groups of processes running on a system. This guide will walk you through setting up and using cgroups on CentOS 7, giving you fine-grained control over resource allocation.

Prerequisites

  • A CentOS 7 system
  • Root or sudo access

Installing the Required Packages

Before proceeding, ensure that you have installed the necessary libcgroup packages. You can install it using the following command:

sudo yum install libcgroup libcgroup-tools

Starting and Enabling the Service

After installing, you’ll need to enable and start the cgconfig service to manage cgroups:

sudo systemctl enable cgconfig sudo systemctl start cgconfig

Configuring cgroups

You can create a cgroup by editing the /etc/cgconfig.conf file. Open it using your favorite text editor (here we’re using vi):

sudo vi /etc/cgconfig.conf

For instance, if you want to limit the CPU and memory resources for a group called limited_group, you would add the following lines:

group limited_group { cpu { cpu.shares = 512; } memory { memory.limit_in_bytes = 512M; } }

After editing, save the file and restart the cgconfig service:

sudo systemctl restart cgconfig

Adding Processes to the cgroup

Once the group is created, you can start adding processes to it. First, find the Process ID (PID) of the process you want to limit:

ps aux | grep [process_name]

Now, you can add the process to your cgroup:

sudo cgclassify -g cpu,memory:limited_group [PID]

Replace [PID] with the Process ID you found earlier.

Automating the cgroup assignment

If you want to automatically assign certain users or processes to this group, you can edit the /etc/cgrules.conf file:

sudo vi /etc/cgrules.conf

Add the following line to associate a user with the limited_group:

username cpu,memory limited_group/

After that, you’ll need to enable and start the cgrulesengd service:

sudo systemctl enable cgrulesengd sudo systemctl start cgrulesengd

Verifying the cgroup Settings

To verify that your cgroup is working as expected, you can inspect the cgroup filesystem usually mounted under /sys/fs/cgroup/. For example:

cat /sys/fs/cgroup/cpu/limited_group/cpu.shares cat /sys/fs/cgroup/memory/limited_group/memory.limit_in_bytes

Conclusion

cgroups are a powerful tool for resource management on Linux systems. With this guide, you have learned how to create a cgroup, configure its resource limits, and assign processes to it on CentOS 7. This should give you a strong foundation for managing resources on your server more effectively.

Happy computing!

Scroll to Top