- системные настройки высоконагруженного сервера
- limits.conf
- sysctl.conf
- Заключение
- limits.conf и лимиты потребления ресурсов для пользователей в Linux
- ulimit в Linux и ограничение ресурсов для пользователя
- How to Set Limits on User Running Processes in Linux
- If You Appreciate What We Do Here On TecMint, You Should Consider:
- How to Limit Process at User Level on Linux
- Check all current limits
- Set ulimit for user
- Set Ulimit for open file
- Set user limit via systemd
- Conclusion
- How to Set Max User Processes on Linux
- Setting Max User Processes
- Set Max User Processes Temporarily
- Set Max User Processes Permanently
- Conclusion
- About the author
- Sidratul Muntaha
системные настройки высоконагруженного сервера
Настройки 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, но такие изменения не сохранятся после перезагрузки, поэтому будем сразу вносить изменения в этот конфиг файл.
Для пользователей 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 сейчас можно увидеть, что ограничение установлено. Получить ту же информацию можно просмотрев лимиты для процесса
Можно указывать идентификатор любого процесса, запущенного от имени пользователя, для которого задали ограничение по памяти
Источник
How to Set Limits on User Running Processes in Linux
One of the Linux’s beauties is that you can control almost everything about it. This gives a system administrator a great control over his system and better utilization of the system resources.
While some might have never thought about doing this, it is important to know that in Linux you can limit how much resource a single user may use and for how long.
In this short topic, we will show you how to limit the number of processes started by user and how to check the current limits and modify them.
Before we go any further there are two things we need to point:
- You need root access to your system to modify the user limits
- You must be extremely careful if you plan to modify these limits
To setup user limits, we will need to edit the following file:
This file is used to apply ulimit created by the pam_module.
The file has the following syntax:
Here we will stop to discuss each of the options:
- Domain – this includes usernames, groups, guid ranges etc
- Type – soft and hard limits
- Item – the item that will be limited – core size, file size, nproc etc
- Value – this is the value for the given limit
A good sample for a limit is:
The above line sets a hard limit of maximum 20 processes on the «student» group.
If you want to see the limits of a certain process has you can simply “cat” the limits file like this:
Where PID is the actual process ID, you can find out process id by using ps command. For more detailed explanation, read our article that says – Find Running Linux Processes and Set Process Limits Per-User Level
So here is an example:
Sample Output
All of the lines are pretty much self explanatory. However if you want to find more the settings you can input in limits.conf file, you can have a look at the manual provided here.
If you have any questions or comments, please do not hesitate to submit them in the comment section below.
If You Appreciate What We Do Here On TecMint, You Should Consider:
TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.
If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.
We are thankful for your never ending support.
Источник
How to Limit Process at User Level on Linux
When the system is heavily used, it would be a big challenge for system administrators to manage resources. Ulimit (user limit) is a powerful command which helps to limit resources on your system.
Sometime, but not very often a single user may start too many processes to make the system unstable. To mitigate this we can use ulimit command to limit the number process each user or group can run.
In this tutorial, we learn how to limit the process at user level on Linux.
With ulimit you can set two kinds of limits:
- Hard limit: This limit is for security purpose. Hard limit can be increased only done by root (ie a non root process cannot go above a hard limit)
- Soft limit: This limit can be changed by process at any time. A non user can set a limit between (0 and hard limit) for its processes.
Check all current limits
You can check all the limits for the currently logined user.
Run the following ulimit command with -a option:
You can see that there are some unlimited settings. These limits can be changed.
Note: The /proc file-system stores the per-process limits in the file system object located at /proc/4548/limits , where ‘4548’ is the process’s PID or process identifier.
Set ulimit for user
You can use ulimit -u to find max user processes or nproc limit.
You can change max user processes by the following command:
If you get any error or unable to change check if you have set any limits in ‘/etc/security/limits.conf’.
Limits can be set for specific user or group in limits.con file.
If you want to set ‘infrateam’ to have more process than ‘testers’ and limit user bob nproc to ’60’, then set as follows:
Here we set limit to open files using ‘nofile’ field. As we set soft limit, user will get warnings when they reach the lower limit.
Set Ulimit for open file
We can use ulimit command to view the limits open files for each user.
Check the user level open file hard limit
Check the user level open file soft limit
If you want to change the current open file limits (soft or hard) you can update in ‘limits.conf’ file.
In our example, we will set the maximum number of files to 16384 for all users of the system.
Reboot your machine and test the new limits configuration
To check Linux system-wide current maximum number of open file, then run the following command:
To change maximum number of open file run following commands:
to make it persistent after reboot update in ‘sysctl.conf’ file
Set user limit via systemd
Earlier we discussed that we can set limits by editing the /etc/security/limits.conf file but systemd would ignore this file.
Systemd by default reads from ‘/etc/systemd/system.conf’ file. Below are systemd limits equivalent to ulimits.
You can set user limit by editing the /etc/systemd/user.conf file.
For example, you can try as below:
Some services that are started via systemd ignore the /etc/security/limits.conf file. To face this issue, you should set the limits in the service definition file.
You need to update the service file as following:
Conclusion
In this tutorial, we learned how to use ulimit command to set limit for processes for a user. I hope you enjoyed reading and please leave your suggestions or feedback in the comment section.
Источник
How to Set Max User Processes on Linux
Setting Max User Processes
A single user has the capability to run a large number of processes. Linux is a multi-user operating system. Now, imagine multiple users running tons of processes. Even if each of the processes does not consume too many hardware resources on its own, the sum of all user processes may eventually hog the entire system. To avoid such a situation, system admins may limit the number of processes that each user can open.
The limit can be imposed temporarily or permanently. Depending on your target scenario, follow the most appropriate method.
Set Max User Processes Temporarily
This method temporarily changes the limit of the target user. If the user restarts the session or the system is rebooted, the limit will reset to the default value.
Ulimit is a built-in tool that is used for this task. Ulimit can impose limits on various resources for a particular user. The only downside (as mentioned earlier) is that it is temporary.
Log in as the target user and check the current process limit.
Next, define the limit to 12345.
Verify the change.
Set Max User Processes Permanently
The following method is more reliable in a real-life scenario. If the user logs out or the system reboots, the change will not disappear.
Here, we will still use the Ulimit tool. However, instead of directly making changes using the ulimit command, we will tweak the system configuration tool that Ulimit uses to assign the limits to the target users.
Check out the limits.conf. command below:
To add an entry to the file, it should be in the following format:
The following list provides a definition for each field:
- domain: A domain can be a user, user group, GUID ranges, etc.
- type: The type of the limit. It can be either hard or soft.
- item: What resource will be limited. For this guide, we’ll be using “nproc”.
- value: The value of the limit.
Next, we will discuss limit types. If you want the domain to have a maximum process limit hovering around a certain value, then you use the soft limit type. If you want the domain to have a maximum process limit at a fixed value, then you use the hard limit type.
As for the item fields, there are a number of these. For the full list, I recommend checking out the limits.conf man page.
Now, back to tweaking the limits.conf file. To edit the file, open it in your favorite text editor. Note that you must run the command with root privileges. Otherwise, the changes cannot be saved.
The following line is just an example. It will set a hard limit of 12345 for the user viktor.
Save the file and close the editor. To take the changes into effect, the user may need to restart the session or the system may have to reboot.
Verify the result.
Conclusion
Limiting max user processes is a common task that system admins may have to perform. Hopefully, this guide was helpful in that regard.
If you are interested in learning more about how to impose limits on other resources, check out the article Linux ulimit command. Ulimit is the primary tool that imposes resource limits on users in Linux.
About the author
Sidratul Muntaha
Student of CSE. I love Linux and playing with tech and gadgets. I use both Ubuntu and Linux Mint.
Источник