Limit conf in linux

limits.conf File To Limit Users, Process In Linux With Examples

limits.conf configuration file is used to limit user, domain, process-related metrics. Limits.conf is related to pam_limits module.

limits.conf Configuration File

There is a configuration file named limits.conf and located at /etc/security/ . The default content of this file is as below. We can see that there are different columns named domain , type , item and value .

As we can see all configurations are commented so they are not effective. There is also a directory which is use to store configuration files in a separate files to maintain easily. This location is /etc/security/limits.d/ . It is by default empty but we can create rules in this directory easily.

limits.conf Syntax

Limits.conf file have a simple and reliable syntax. This syntax is defined to easily set context, type, limits and related values. We will look all of this terms below.

Domain

While limits configuration we need to specify context. This content can be defined in various ways and various parameters. The first column of the rule is the domain. A domain can be one of the following value.

  • username
  • groupname
  • * specifies all
  • userid
  • groupid

While limiting there is two type of limit implementation. These are called hard and soft . Hard limits are set by root and enforced by kernel. The hard limits can not be exceeded. Soft limits have some range overload. But the overload can be for a little time and can not continue forever.

Items are the core of limits. Items are used to specify the item the limit will be applied. For example, if we want to limit the maximum process number we will use nproc numbers. Here are some of the items that can be used to for limit operation.

  • fsize specifies maximum file size
  • nofile specifies maximum number of file size
  • cpu specifies maximum CPU time
  • nproc specifies maximum number of process
  • maxlogins specifies maximum number of logins
  • maxsyslogins specifies maximum number of logins for all users

Specify User For Limit

Now we can start with examples. As we stated we can limit relevant items according to the user name. In the following rule, we will specify a limit for username ismail where we specify the user name in the first column.

In this example we set core or CPU limit for value 1000000 for username ismail as hard

Specify Group For Limit

In this example, we can specify the limit for a user group name. This type of limitation can be useful if we want to restrict some user group names.

In this example we specify apache group name to limit process number as maximum 20

Use Wildcard For Limit

While specifying the domain or the users and groups we may need to set limits for all users and groups in a system. Here we will use * or a wildcard for this.

In this example we set rss limit for all users and groups in this systems.

Specify User ID Range For Limit

We want to specify limit some users. But they are not in a user group and we do not want or can create groups for these groups. Specifying limits one by one is a problem. We can specify multiple users like below. But the restriction is that we will specify the range.

The rule above will be applied to the users those User ID’s are between 1000 and 1010 . The : operator used to specify the range.

Specify Group ID Range For Limit

The similar definition like previous user range is group range. We will specify group ID range like below.

Читайте также:  Как узнать пароль пользователя системы windows

In this example, the rules will be applied for the group ID between 500 and 510. We use @ operator to specify ID’s as a group and : for range.

Limit Number of Process

Now we will start to look at different item types to use. There are more items than described here but these are the most popular ones. The first example is limiting the number of processes for a user.

In the example, we limit the process number with nproc item. The user the rule will apply is ismail and the maximum number of the process for this user can own is 20

Limit CPU Time

Another useful item to limit is CPU time. We can set limits about the CPU time .

In this example we applied maximum 10000 cycles for user ismail by using cpu item.

Limit Number Of Open File

We can limit the numbers of files a user can open in time. This can be useful to prevent disk bottlenecks if the system has a lot of users those access files.

In this example we specify that the user ismail can only open 512 files or file descriptors with nofile item.

Limit Number Of Logins

By default, a user can have infinite numbers of connections, sessions, or logins in a system. This may create some security or performance problems for the systems. We can set some limits on this.

In these examples, we limit the student group’s user’s login count. We use maxlogins for each user in the student group. The maximum number of login can not be more than 4 .

Limit Number Of System Logins

In the previous example, we have restricted maximum logins as a user base. we can also specify the total number of logins in system-wide. This restriction will be effective in a general manner.

In this example, we restrict all users and groups but actually, this is not a user or group based restriction. We set this rule system-wide and use maxsyslogin item as 40

Limit Maximum File Size

We may want to restrict file size. This restriction can be useful in temp or similar usage type files.

In this example, we limit the student’s single file size as 4000000 . This is a presentation of KB or kilobyte. So the example means 4 GB . We use fsize as item type.

Источник

системные настройки высоконагруженного сервера

Настройки Linux по-умолчанию не годятся для высоких нагрузок. Под высокими нагрузками я понимаю от 10000 запросов в секунду. В данной статье рассмотрим два «переключателя», покрутив которые мы добьемся от сервера устойчивости и отзывчивости при высоких нагрузках. Эти переключатели: limits.conf и sysctl.conf

limits.conf

Это конфигурационный файл для pam_limits.so модуля. Он определяет ulimit лимиты для пользователей и групп. В Linux есть системные вызовы: getrlimit() и setrlimit() для получения и установления лимитов на системные ресурсы. Конфигурация по-умолчанию лежит в /etc/security/limits.conf. Также присутствует возможность добавлять отдельные конфиги для приложений в /etc/security/limits.d. Для того, чтобы сервер держал большую нагрузку, нужно увеличить некоторые лимиты. Посмотрим, какие лимиты у нас стоят по-умолчанию. Запустим под рутом.

Обратим внимание на open files, max user processes и max locked memory. Это стандартные ограничения, которые нужно убрать, если хотим держаться под нагрузкой. Перед изменениями хочу предупредить, что если железо недостаточно мощное, то ваш сервер может подвергнуться атаке типа fork bomb, так что аккуратно раздавайте права на сервере.

Приведем /etc/security/limits.conf к такому виду.

В файле мы устанавливаем мягкий и жесткий лимиты на количество запущенных процессов, открытых файлов (читай портов) для всех пользователей и неограниченный лок памяти для рута.

Хочу поподробнее рассказать, почему для открытых файлов было выбрано ограничение в 1048576. Это волшебное число захардкожено в ядре, чтоб поставить больше, нужно пересобирать ядро. Более развернуто на эту тему отвечают на stackoverflow и вот здесь.

Изменения вступят в силу или после перезагрузки или после нового логина или создания сессии ssh. Проверить, включается ли модуль pam_limits можно в файлах /etc/pam.d Для Debian есть статья в wiki на эту тему: https://wiki.debian.org/Limits

sysctl.conf

В /etc/sysctl.conf настраиваются параметры ядра, модулей и других подсистем. По сути, можно вручную менять значения псевдо-фс /proc, но такие изменения не сохранятся после перезагрузки, поэтому будем сразу вносить изменения в этот конфиг файл.

Читайте также:  Настройка gns3 on windows

Для пользователей systemd этот файл уже не играет роли. Если вы вдруг используете systemd, вам нужно править файлы в /etc/sysctl.d/. Подробнее читайте на http://www.freedesktop.org/software/systemd/man/sysctl.d.html

Вот пример моего sysctl.conf для высоконагруженной системы.

Подробно про все опции, можно прочитать в

Или, например, здесь. А тут написано как люди выдерживают миллион pps в секунду и приведены примеры используемых sysctl.conf

После изменения sysctl.conf применим наши правки.

После перезагрузки все изменения будут применяться автоматически.

Заключение

Все вышеописанное применялось мной на работе для высоконагруженного сервера, который перед выкаткой в прод тестировался замечательным Yandex танком и держал нагрузку порядка 20000 rps. Стоит учесть, что сам по себе Linux не обеспечит вам стойкости под нагрузкой, если ваш софт ломается при 100 rps. Тут уже вас может спасти балансировка нагрузки. Смотрите в сторону HAProxy, LVS, Keepalived. Удачного прохождения высоких нагрузок!

Источник

limits.conf и лимиты потребления ресурсов для пользователей в Linux

Прежде всего, как выяснить процессы каких пользователей потребляют больше всего ресурсов CPU оперативной памяти.

Для текущего момента посмотреть процессы можно при помощи утилиты ps

ps aux —sort=%cpu | grep -v ‘root’ | head -n 35

ps aux —sort=%mem | grep -v ‘root’ | head -n 35

Команды выведут сортированные списки процессов в одной из колонок каждого списка будет указано имя пользователя. Процессы, запущенные от имени root показываться не будут и выведутся только 35 самых активных процессов.

Подобным образом статистику посмотреть не удасться, например, для веб-сервера с mod_php, однаако в большинстве случаев это как раз та информация, которая нужна для того чтобы выбрать пользователей для которых нужно предусмотреть ограничения.

Ограничения нужны на нагруженных серверах, они существует у каждого хостинг провайдера.

Лимитировать количество процессов можно используя механизм ядра cgroups — на практике проще всего установить ограничения отредактировав файл /etc/security/limits.conf и перезагрузив сервер.

Изменять /etc/security/limits.conf может только пользователь root или другой пользователь работающий из под sudo.

Файл хорошо задокументирован, вся необходимая информация находится в нем в комментариях

В общем виде любое правило выглядит так:

domain — это пользователь или группа, для которых лимитируем ресурсы

type — тип ограничения: soft или hard, ограничение soft может быть переопределено пользователем.

item — ресурс, который ограничиваем — обычно это cpu (в минутах) или as — максимальное количество оперативной памяти (в Кб); также можно задать nice level, который не сможет быть превышен процессами пользователя/группы (минимум 20, максимум -19); здесь же можно задать chroot (только для debian)

item — само численное значение

Как уже упоминалось — для того чтобы изменения вступили в силу нужна перезагрузка.

ulimit в Linux и ограничение ресурсов для пользователя

Soft лимиты пользователь может переопределить используя ulimit

Выполнение команды с аргументом -a выведет актуальные ограничения

ulimit -as 1500000
core file size (blocks, -c) 0
data seg size (kbytes, -d) unlimited
scheduling priority (-e) 0
file size (blocks, -f) unlimited
pending signals (-i) 14685
max locked memory (kbytes, -l) 64
max memory size (kbytes, -m) unlimited
open files (-n) 1024
pipe size (512 bytes, -p) 8
POSIX message queues (bytes, -q) 819200
real-time priority (-r) 0
stack size (kbytes, -s) 8192
cpu time (seconds, -t) unlimited
max user processes (-u) 14685
virtual memory (kbytes, -v) unlimited
file locks (-x) unlimited

Ключи из вывода можно брать и использовать в командах, которые будут задавать ограничения для текущей терминальной сессии.

Дополнительно следует указывать тип ограничения:

-H — hard

-S — soft

Если не указывать ничего лимиты будут заданы жестко. hard здесь можно задать для текущего пользователя даже без прав root, но изменения не сохранятся после перезагрузки и чтобы ограничения были установлены постоянно нужно редактировать файл, который был рассмотрен ранее.

Создадим ограничение по оперативной памяти в 1500 Мб для пользователя

Выполнив ulimit -Hm сейчас можно увидеть, что ограничение установлено. Получить ту же информацию можно просмотрев лимиты для процесса

Можно указывать идентификатор любого процесса, запущенного от имени пользователя, для которого задали ограничение по памяти

Источник

limits.conf(5) — Linux man page

limits.conf — configuration file for the pam_limits module

Description

The pam_limits.so module applies ulimit limits, nice priority and number of simultaneous login sessions limit to user login sessions. This description of the configuration file syntax applies to the /etc/security/limits.conf file and *.conf files in the /etc/security/limits.d directory.

Читайте также:  Windows для samsung p29

The syntax of the lines is as follows:

The fields listed above should be filled as follows:

• a username • a groupname, with @group syntax. This should not be confused with netgroups. • the wildcard *, for default entry. • the wildcard %, for maxlogins limit only, can also be used with %group syntax. If the % wildcard is used alone it is identical to using * with maxsyslogins limit. With a group specified after % it limits the total number of logins of all users that are member of the group. • an uid range specified as : . If min_uid is omitted, the match is exact for the max_uid. If max_uid is omitted, all uids greater than or equal min_uid match. • a gid range specified as @ : . If min_gid is omitted, the match is exact for the max_gid. If max_gid is omitted, all gids greater than or equal min_gid match. For the exact match all groups including the user’s supplementary groups are examined. For the range matches only the user’s primary group is examined. • a gid specified as %: applicable to maxlogins limit only. It limits the total number of logins of all users that are member of the group with the specified gid. hard for enforcing hard resource limits. These limits are set by the superuser and enforced by the Kernel. The user cannot raise his requirement of system resources above such values. soft for enforcing soft resource limits. These limits are ones that the user can move up or down within the permitted range by any pre-existing hard limits. The values specified with this token can be thought of as default values, for normal system usage. for enforcing both soft and hard resource limits together.

Note, if you specify a type of ‘-‘ but neglect to supply the item and value fields then the module will never enforce any limits on the specified user/group etc. . core limits the core file size (KB) data maximum data size (KB) fsize maximum filesize (KB) memlock maximum locked-in-memory address space (KB) nofile maximum number of open files rss maximum resident set size (KB) (Ignored in Linux 2.4.30 and higher) stack maximum stack size (KB) cpu maximum CPU time (minutes) nproc maximum number of processes as address space limit (KB) maxlogins maximum number of logins for this user except for this with uid=0 maxsyslogins maximum number of all logins on system priority the priority to run user process with (negative values boost process priority) locks maximum locked files (Linux 2.4 and higher) sigpending maximum number of pending signals (Linux 2.6 and higher) msgqueue maximum memory used by POSIX message queues (bytes) (Linux 2.6 and higher) nice maximum nice priority allowed to raise to (Linux 2.6.12 and higher) values: [-20,19] rtprio maximum realtime priority allowed for non-privileged processes (Linux 2.6.12 and higher) All items support the values -1, unlimited or infinity indicating no limit, except for priority and nice.

If a hard limit or soft limit of a resource is set to a valid value, but outside of the supported range of the local system, the system may reject the new limit or unexpected behavior may occur. If the control value required is used, the module will reject the login if a limit could not be set.

In general, individual limits have priority over group limits, so if you impose no limits for admin group, but one of the members in this group have a limits line, the user will have its limits set according to this line.

Also, please note that all limit settings are set per login. They are not global, nor are they permanent; existing only for the duration of the session.

In the limits configuration file, the ‘#‘ character introduces a comment — after which the rest of the line is ignored.

The pam_limits module does report configuration problems found in its configuration file and errors via syslog(3).

Examples

These are some example lines which might be specified in /etc/security/limits.conf.

See Also

Author

pam_limits was initially written by Cristian Gafton

Источник

Оцените статью