- How to Increase Number of Open Files Limit in Linux
- Find Linux Open File Limit
- Check Hard Limit in Linux
- Check Soft Limits in Linux
- How to Check System wide File Descriptors Limits in Linux
- Set User Level Open File limits in Linux
- Final thoughts
- If You Appreciate What We Do Here On TecMint, You Should Consider:
- linux-notes.org
- Увеличить Max Open File Limit в Unix/Linux
- Увеличить Max Open File Limit в Linux
- Увеличить Max Open File Limit в Mac OS X
- Увеличюем nginx worker_rlimit_nofile в nginx ( на уровне Nginx)
- Включение ограничений на основе PAM в Unix/Lixux
- 3 thoughts on “ Увеличить Max Open File Limit в Unix/Linux ”
- Добавить комментарий Отменить ответ
- Ошибка too many open files в Linux
- Ошибка too many open files Linux
- Выводы
- How to fix ‘Too Many Open Files’ in Linux
- Where can we find error, ‘Too Many Open Files’?
- ‘Too Many Open Files’ error & Open File Limits in Linux
- Increase the Max Open File Limit in Linux
- Increase the Open File Descriptor Limit per service
- Set Max Open Files Limit for Nginx & Apache
- Alter the Open File Limit for Current Session
- Conclusion
- Related posts:
- PREVENT YOUR SERVER FROM CRASHING!
How to Increase Number of Open Files Limit in Linux
In Linux, you can change the maximum amount of open files. You may modify this number by using the ulimit command. It grants you the ability to control the resources available for the shell or process started by it.
In this short tutorial we will show you how to check your current limit of open files and files descriptions, but to do so, you will need to have root access to your system.
First, Lets see how we can find out the maximum number of opened file descriptors on your Linux system.
Find Linux Open File Limit
The value is stored in:
The number you will see, shows the number of files that a user can have opened per login session. The result might be different depending on your system.
For example on a CentOS server of mine, the limit was set to 818354, while on Ubuntu server that I run at home the default limit was set to 176772.
If you want to see the hard and soft limits, you can use the following commands:
Check Hard Limit in Linux
Check Soft Limits in Linux
To see the hard and soft values for different users, you can simply switch user with “su” to the user which limits you want to check.
How to Check System wide File Descriptors Limits in Linux
If you are running a server, some of your applications may require higher limits for opened file descriptors. A good example for such are MySQL/MariaDB services or Apache web server.
You can increase the limit of opened files in Linux by editing the kernel directive fs.file-max . For that purpose, you can use the sysctl utility.
For example, to increase open file limit to 500000, you can use the following command as root:
You can check the current value for opened files with the following command:
With the above command the changes you have made will only remain active until the next reboot. If you wish to apply them permanently, you will have to edit the following file:
Add the following line:
Of course, you can change the number per your needs. To verify the changes again use:
Users will need to logout and login again for the changes to take effect. If you want to apply the limit immediately, you can use the following command:
Set User Level Open File limits in Linux
The above examples, showed how to set global limits, but you may want to apply limits per user basis. For that purpose, as user root, you will need to edit the following file:
If you are a Linux administrator, I suggest you that you become very familiar with that file and what you can do to it. Read all of the comments in it as it provides great flexibility in terms of managing system resources by limiting users/groups on different levels.
The lines that you should add take the following parameters:
Here is an example of setting a soft and hard limits for user marin:
Final thoughts
This brief article showed you a basic example of how you can check and configure global and user level limits for maximum number of opened files.
While we just scratched the surface, I highly encourage you to have a more detailed look and read regarding /etc/sysctl.conf and /etc/security/limits.conf and learn how to use them. They will be of great help for you one day.
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.
Источник
linux-notes.org
Несколько раз я сталкивался с ошибкой «Too many open files»(Слишком много открытых файлов) на сервере с высокой нагрузкой. Это означает, что сервер исчерпывает ресурс на максимальный предел открытых файлов (max open file limit). Теперь вопрос в том, как я могу увеличить лимиты открытых файлов на Linux? Да все очень просто, в своей статье «Увеличить Max Open File Limit в Unix/Linux» покажу как это выполняется.
Увеличить Max Open File Limit в Unix/Linux
Приведу команды на различные Unix/Linux ОС
Увеличить Max Open File Limit в Linux
Для начала проверим какой предел установлен в ОС:
Увеличиваем данный предел в Linux
Мы можем увеличить лимиты для открытых файлов:
-===ВРЕМЕННО===-
Если есть необходимость увеличить лимит временно (для тестирования, например), то можно это сделать так:
Вот еще один пример:
-===ПОСТОЯННО===-
Если есть необходимость увеличить лимит навсегда, то можно это сделать так:
Эти настройки будут сохраняться даже после перезагрузки системы. После добавления конфигурации в файл, выполните следующую команду, чтобы изменения вступили в силу:
Настройка лимитов для каждого пользователя
Проверка установленных лимитов
Используйте следующую команду, чтобы увидеть максимальное чисто для открытых файлов:
Подключаемся от пользователя (у меня это nginx):
Проверяем параметры Hard лимитов :
В консоле, можно ввести данную команду (очень удобно отображает):
Проверяем параметры лимитов Soft :
Увеличить Max Open File Limit в Mac OS X
Выполним проверку лимитов с помощью:
- Первый аргумент — soft limit.
- Второй аргумент — hard limit.
Можно прописать в файл:
Увеличюем nginx worker_rlimit_nofile в nginx ( на уровне Nginx)
В nginx также можно увеличить лимиты с директивой worker_rlimit_nofile, которая позволяет увеличить этот лимит, если это не хватает данного ресурса на лету на уровне процесса:
И прописываем (редактируем):
После чего, проверяем конфигурацию nginx и перезапускаем его:
Save and close the file. Reload nginx web server, enter:
В комментариях писали что нельзя установить данные лимиты для Kali Linux. Вот, решил показать наглядный пример:
ulimit в Kali Linux
Включение ограничений на основе PAM в Unix/Lixux
Для Debian/Ubuntu
Редактируем файл (Debian/Ubuntu):
Открываем еще один файл:
И, приводим к виду:
И выполняем рестарт:
Для CentOS/RedHat/Fedora
Редактируем файл (Debian/Ubuntu):
Открываем еще один файл:
И, приводим к виду:
И выполняем рестарт:
У меня все! Статья «Увеличить Max Open File Limit в Unix/Linux», завершено.
3 thoughts on “ Увеличить Max Open File Limit в Unix/Linux ”
в kali linux не работает смена хард и софт лимитов. всё равно пишет 4096 и 1024 соответственно.
Можно! Что-то делаете не так. Я выложил скриншот в статье и показал что можно все сделать.
Мужикам на картинке к статье явно не повезло.
Свет приглушён, явно видно зелёный оттенок табличек аварийного освещения — либо дело за полночь, либо у них блекаут и работают от дизеля.
Сидят за консолью. По сети, оно, похоже, уже не отвечает. Плохо дело.
Стул притащили. Значит, давно не отвечает. Надо было прописать MAX OPEN FILE LIMIT заранее, а не когда уже навернулось.
Добавить комментарий Отменить ответ
Этот сайт использует Akismet для борьбы со спамом. Узнайте, как обрабатываются ваши данные комментариев.
Источник
Ошибка too many open files в Linux
Если вы работали с программами, которым приходится обрабатывать очень большое количество файловых дескрипторов, например с распределенными базами данных, такими, как Elasticsearch, то вы, наверняка, сталкивались с ошибкой «too many open files в Linux».
В этой небольшой статье мы разберемся, что означает эта ошибка, а также как её исправить в различных ситуациях.
Ошибка too many open files Linux
Дословно эта ошибка означает, что программа открыла слишком много файлов и больше ей открывать нельзя. В Linux установлены жёсткие ограничения на количество открываемых файлов для каждого процесса и пользователя.
Посмотреть, сколько файлов можно открыть в вашей файловой системе, можно, выполнив команду:
Посмотреть текущие ограничения количества открытых файлов для пользователя можно командой:
Утилита ulimit возвращает два вида ограничений — hard и soft. Ограничение soft вы можете менять в любую сторону, пока оно не превышает hard. Ограничение hard можно менять только в меньшую сторону от имени обычного пользователя. От имени суперпользователя можно менять оба вида ограничений так, как нужно. По умолчанию отображаются soft-ограничения:
Чтобы вывести hard, используйте опцию -H:
Вы можете изменить ограничение, просто передав в ulimit новое значение:
Но поскольку hard-ограничение составляет 4000, то установить лимит больше этого значения вы не сможете. Чтобы изменить настройки ограничений для пользователя на постоянной основе, нужно настроить файл /etc/security/limits.conf. Синтаксис у него такой:
имя_пользователя тип_ограничения название_ограничения значение
Вместо имени пользователя можно использовать звездочку, чтобы изменения применялись ко всем пользователям в системе. Тип ограничения может быть soft или hard. Название — в нашем случае нужно nofile. И последний пункт — нужное значение. Установим максимум — 1617596.
sudo vi /etc/security/limits.conf
* hard nofile 1617596
* soft nofile 1617596
Нужно установить значение для soft и hard параметра, если вы хотите, чтобы изменения вступили в силу. Также убедитесь, что в файле /etc/pam.d/common-session есть такая строчка:
session required pam_limits.so
Если её нет, добавьте в конец. Она нужна, чтобы ваши ограничения загружались при авторизации пользователя.
Если вам нужно настроить ограничения только для определенного сервиса, например Apache или Elasticsearch, то для этого не обязательно менять все настройки в системе. Вы можете сделать это с помощью systemctl. Просто выполните:
sudo systemctl edit имя_сервиса
И добавьте в открывшейся файл такие строки:
[Service]
LimitNOFILE=1617596
LimitNOFILESoft=1617596
Здесь мы устанавливаем максимально возможное ограничение как для hard- так и для soft-параметра. Дальше нужно закрыть этот файл и обновить конфигурацию сервисов:
sudo systemctl daemon-reload
Затем перезагрузить нужный сервис:
sudo systemctl restart имя_сервиса
Убедится, что для вашего сервиса применились нужные ограничения, можно, открыв файл по пути /proc/pid_сервиса/limits. Сначала смотрим PID нужного нам сервиса:
ps aux | grep elasticsearch
Затем смотрим информацию:
Выводы
В этой небольшой статье мы разобрали, что делать, если возникает ошибка «слишком много открытых файлов Linux», а также как изменять ограничения на количество открытых файлов для пользователя и процесса в Linux.
Источник
How to fix ‘Too Many Open Files’ in Linux
by Nicky Mathew | Nov 18, 2020
Linux users often come across the error, ‘Too Many Open Files’ due to high load in the server, leaving it hard for us to open multiple files.
We, at Bobcares have experienced similar error and our Server Administration Team have come up with effective solutions.
Today, let’s check how to find the limit of maximum number of open files set by Linux and how we alter it for an entire host, individual service or a current session.
Where can we find error, ‘Too Many Open Files’?
Since Linux has set a maximum open file limit by default, the system has a method for restricting the number of various resources a process can consume.
Usually the ‘Too Many Open Files’ error is found on servers with an installed NGINX/httpd web server or a database server (MySQL/MariaDB/PostgreSQL).
For example, when an Nginx web server exceeds the open file limit, we come across an error:
To find the maximum number of file descriptors a system can open, run the following command:
The open file limit for a current user is 1024. We can check it as follows:
There are two limit types: Hard and Soft. Any user can change a soft limit value but only a privileged or root user can modify a hard limit value.
However, the soft limit value cannot exceed the hard limit value.
To display the soft limit value, run the command:
To display the hard limit value:
‘Too Many Open Files’ error & Open File Limits in Linux
Now we know that these titles mean that a process has opened too many files (file descriptors) and cannot open new ones. In Linux, the maximum open file limits are set by default for each process or user and the values are rather small.
We, at Bobcares have monitored this closely and have come up with a few solutions:
Increase the Max Open File Limit in Linux
A large number of files can be opened if we change the limits in our Linux OS. In order to make new settings permanent and prevent their reset after a server or session restart, make changes to /etc/security/limits.conf. by adding these lines:
- hard nofile 97816
- soft nofile 97816
If it is using Ubuntu, add this line as well:
These parameters allow to set open file limits after user authentication.
After making the changes, reload the terminal and check the max_open_files value:
Increase the Open File Descriptor Limit per service
A change in the limit of open file descriptors for a specific service, rather than for an entire operating system is possible.
For example, if we take Apache, to change the limits, open the service settings using systemctl:
Once the service settings is open, add the limits required. For example;
After making the changes, update the service configuration and restart it:
To ensure the values have changed, get the service PID:
For example, if the service PID is 3724:
Thus, we can change the values for the maximum number of open files for a specific service.
Set Max Open Files Limit for Nginx & Apache
In addition to changing the limit on the number of open files to a web server, we should change the service configuration file.
For example, specify/change the following directive value in the Nginx configuration file /etc/nginx/nginx.conf:
While configuring Nginx on a highly loaded 8-core server with worker_connections 8192, we need to specify
Then restart Nginx.
For apache, create a directory:
Then create the limit_nofile.conf file:
Do not forget to restart httpd.
Alter the Open File Limit for Current Session
To begin with, run the command:
Once the terminal is closed and a new session is created, the limits will get back to the original values specified in /etc/security/limits.conf.
To change the general value for the system /proc/sys/fs/file-max, change the fs.file-max value in /etc/sysctl.conf:
[Despite all the above solutions if the issue still prevail, don’t panic. We have our Experienced Tech Team working round the clock to help you fix it for you.]
Conclusion
To conclude, today, we figured how our Support Engineers solve the error, ‘Too Many Open Files’ and discussed options to change the default limits set by Linux.
We saw that the default value of open file descriptor limit in Linux is too small, and discussed a few options for changing these limits of the server.
Related posts:
PREVENT YOUR SERVER FROM CRASHING!
Never again lose customers to poor server speed! Let us help you.
Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.
Источник