Очень часто при работе на высоконагруженных Linux серверах могут возникать ошибки “too many open files”. Это означает, что процесс открыл слишком много файлов (читай файловых дескрипторов) и не может открыть новые. В Linux ограничения “max open file limit“ установлены по умолчанию для каждого процесса и пользователя, и они не слишком высокие.
В данной статье мы рассмотрим, как проверить текущие ограничения на количество открытых файлов в Linux, как изменить этот параметр для всего сервера, для отдельных сервисов и для сеанса. Статья применима для большинства современных дистрибутивов Linux (Debian, Ubuntu, CentOS, RHEL, Oracle Linux, Rocky и т.д.)
Содержание:
- Ошибка: Too many open files и лимиты на количество открытых файлов в Linux
- Глобальные ограничения на количество открытых файлов в Linux
- Увеличить лимит открытых файловых дескрипторов для отдельного сервиса
- Увеличить количество открытых файлов для Nginx и Apache
- Лимиты file-max для текущей сессии
Ошибка: Too many open files и лимиты на количество открытых файлов в Linux
Чаще всего ошибку “too many open files“. Чаще всего эта ошибка встречается на серверах с установленным веб-сервером NGINX/httpd, сервером БД (MySQL/MariaDB/PostgreSQL), при чтении большого количества логов. Например, когда веб-серверу Nginx не хватает лимита для открытия файлов, вы получите ошибку:
socket () failed (24: Too many open files) while connecting to upstream
Или:
HTTP: Accept error: accept tcp [::]:<port_number>: accept4: too many open files.
В Python:
OSError: [Errno 24] Too many open files.
Максимально количество файловых дескрипторов, которые могут быть открыты в вашей файловой системе всеми процессами можно узнать так:
# cat /proc/sys/fs/file-max
Чтобы узнать, сколько файлов открыто сейчас, выполните:
$ cat /proc/sys/fs/file-nr
7744 521 92233720
- 7744 — суммарное количество открытых файлов
- 521– число открытых файлов, но которые сейчас не используются
- 92233720– максимальное количество файлов, которое разрешено открывать
В Linux ограничение на максимальное количество открытых файлов можно натсроить на нескольких уровнях:
- Ядра ОС
- Сервиса
- Пользователя
Чтобы вывести текущее ограничение на количество открытых файлов в ядре Linux, выполните:
# sysctl fs.file-max
fs.file-max = 92233720
Выведем ограничение на количество открытых файлов для одного процесса текущего пользователя:
# ulimit -n
По умолчанию количество файлов для одного процесса этого ограничено числом 1024.
Выведем максимальное количество для одного пользователя (max user processes):
# ulimit –u
5041
Умножаем 1024 * 5041 дает нам 5161984 – это максимально количество открытых файлов всеми процессами пользователя.
В Linux есть два типа ограничений на количество открытых файлов: Hard и Soft. Soft ограничения носят рекомендательный характер, при превышении значения пользователь будет получать предупреждения. Если количество открытых файлов превысило hard лимит, пользователь не сможет открыть новые файлы пока не будет закрыты ранее открытые.
Для просмотра текущих лимитов используется команда ulimit с опцией
-S
(soft) или
-H
(hard) и параметром
-n
(the maximum number of open file descriptors).
Для вывода Soft-ограничения:
# ulimit -Sn
Для вывода Hard-ограничения:
# ulimit -Hn
Глобальные ограничения на количество открытых файлов в Linux
Чтобы разрешить всем сервисам открывать большее количество файлов, можно изменить лимиты на уровне всей ОС Linux. Чтобы новые настройки работали постоянно и не сбрасывались при перезапуске сервера или сессии, нужно поправить файл /etc/security/limits.conf. Строки с разрешениями выглядит так:
Имя_пользователя тип_огрничение название_ограничения значение
Например:
apache hard nofile 978160 apache soft nofile 978160
Вместо имени пользователя можно указать
*
. Это означает, что это ограничение будет применяться для всех пользователей Linux:
* hard nofile 97816 * soft nofile 97816
Например, вы получили ошибку too many open files для nginx. Проверьте, сколько файлов разрешено открывать процессу этому пользователю:
$ sudo -u nginx bash -c 'ulimit -n'
1024
Для нагруженного сервера этого недостаточно. Добавьте в /etc/security/limits.conf строки
nginx hard nofile 50000 nginx soft nofile 50000
В старых ядрах Linux значение fs.file-max может быть равно 10000. Поэтому проверьте это значение и увеличьте его, чтобы оно было больше чем ограничение в limits.conf:
# sysctl -w fs.file-max=500000
Это временно увеличит лимит. Чтобы новые настройки стали постоянными, нужно добавить в файл /etc/sysctl.conf строку:
fs.file-max = 500000
Проверьте, что в файле /etc/pam.d/common-session (Debian/Ubuntu или /etc/pam.d/login для CentOS/RedHat/Fedora) есть строчка:
session required pam_limits.so
Если нет, добавьте ее в конец. Она нужна, чтобы ограничения загружались при авторизации пользователя.
После изменений, перезапустите терминал и проверьте значение лимита max_open_files:
# ulimit -n
97816
Увеличить лимит открытых файловых дескрипторов для отдельного сервиса
Вы можете изменить лимит на количество открытых файловых дескрипторов для конкретного сервиса, а не для всей системы. Рассмотрим на примере apache. Чтобы изменить значения, откройте настройки службы через systemctl:
# systemctl edit httpd.service
Добавьте необходимые лимиты, например:
[Service] LimitNOFILE=16000 LimitNOFILESoft=16000
После изменения, нужно обновить конфигурацию сервиса и перезапустить его:
# systemctl daemon-reload
# systemctl restart httpd.service
Чтобы проверить, изменились ли значения, нужно получить PID сервиса:
# systemctl status httpd.service
Например, вы определил PID сервиса 32724:
# cat /proc/32724/limits | grep "Max open files”
Значение должно быть 16000.
Так вы изменили значения Max open files для конкретного сервиса.
Увеличить количество открытых файлов для Nginx и Apache
После того, как вы увеличил ограничения на количество открытых файлов для сервера, нужно также поправить конфигурационный файл службы. Например, для веб-сервера Nginx в файле конфигурации /etc/nginx/nginx.conf нужно задать значение в директиве:
worker_rlimit_nofile 16000
Директива worker_rlimit_nofile задает ограничение на количество файлов, открытых в рабочем процессе (
RLIMIT_NOFILE
). В Nginx файловые дескрипторы нужны для возврата статического файла из кэша для каждого подключения клиента. Чем больше пользователей использует ваш сервер и чем больше статических файлов отдает nginx, тем большее количество дескрипторов используется. Сверху максимальное количество дескрипторов ограничивается на уровне ОС и/или сервиса. При превышении количеств открытых файлов nginx появится ошибка
socket() failed (24: Too many open files) while connecting to upstream
.
При настройке Nginx на высоконагруженном 8-ядерном сервере с worker_connections 8192 нужно в worker_rlimit_nofile указать 8192*2*8 (vCPU) = 131072.
После чего выполнить рестарт Nginx:
# nginx -t && service nginx -s reload
Чтобы увидеть чисто открытых файлов для процессов пользователя nginx:
# su nginx
# ulimit –Hn
# for pid in `pidof nginx`; do echo "$(< /proc/$pid/cmdline)"; egrep 'files|Limit' /proc/$pid/limits; echo "Currently open files: $(ls -1 /proc/$pid/fd | wc -l)"; echo; done
Для apache, нужно создать директорию:
# mkdir /lib/systemd/system/httpd.service.d/
После этого создайте файл limit_nofile.conf:
# nano /lib/systemd/system/httpd.service.d/limit_nofile.conf
И добавьте в него:
[Service] LimitNOFILE=16000
Не забудьте перезапустить сервис httpd.
Лимиты file-max для текущей сессии
Чтобы изменить лимиты на открытые файлы в рамках текущей сессии пользователя, выполните команду:
# ulimit -n 3000
Если указать здесь значение большее, чем заданное в hard limit, появится ошибка:
-bash: ulimit: open files: cannot modify limit: Operation not permitted
Когда вы завершите текущую сессию терминала и откроете новую, лимиты вернутся к начальным значениям, указанным в файле /etc/security/limits.conf.
В данной статье мы разобрались, как решить проблему с недостаточным лимитом для открытых файловых дескрипторов в Linux и рассмотрели несколько вариантов изменения лимитов на сервере.
Если вы работали с программами, которым приходится обрабатывать очень большое количество файловых дескрипторов, например с распределенными базами данных, такими, как Elasticsearch, то вы, наверняка, сталкивались с ошибкой «too many open files в Linux».
В этой небольшой статье мы разберемся, что означает эта ошибка, а также как её исправить в различных ситуациях.
Дословно эта ошибка означает, что программа открыла слишком много файлов и больше ей открывать нельзя. В Linux установлены жёсткие ограничения на количество открываемых файлов для каждого процесса и пользователя.
Посмотреть, сколько файлов можно открыть в вашей файловой системе, можно, выполнив команду:
cat /proc/sys/fs/file-max
Посмотреть текущие ограничения количества открытых файлов для пользователя можно командой:
ulimit -n
Утилита ulimit возвращает два вида ограничений — hard и soft. Ограничение soft вы можете менять в любую сторону, пока оно не превышает hard. Ограничение hard можно менять только в меньшую сторону от имени обычного пользователя. От имени суперпользователя можно менять оба вида ограничений так, как нужно. По умолчанию отображаются soft-ограничения:
ulimit -nS
Чтобы вывести hard, используйте опцию -H:
ulimit -nH
Вы можете изменить ограничение, просто передав в ulimit новое значение:
ulimit -n 3000
Но поскольку 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
Затем смотрим информацию:
cat /proc/8388/limits
Выводы
В этой небольшой статье мы разобрали, что делать, если возникает ошибка «слишком много открытых файлов Linux», а также как изменять ограничения на количество открытых файлов для пользователя и процесса в Linux.
Статья распространяется под лицензией Creative Commons ShareAlike 4.0 при копировании материала ссылка на источник обязательна .
Об авторе
Основатель и администратор сайта losst.ru, увлекаюсь открытым программным обеспечением и операционной системой Linux. В качестве основной ОС сейчас использую Ubuntu. Кроме Linux, интересуюсь всем, что связано с информационными технологиями и современной наукой.
Very often ‘too many open files’ errors occur on high-load Linux servers. It means that a process has opened too many files (file descriptors) and cannot open new ones. On Linux, the “max open file limit” is set by default per process or user and the values are rather small.
In this article, we’ll look at how to check the current limits on the maximum number of open files in Linux, and how to change this setting globally for the entire server, for specific services, and for a user session. The article is applicable to most modern Linux distros (Debian, Ubuntu, CentOS, RHEL, Oracle Linux, Rocky, etc.)
Contents:
- ‘Too Many Open Files’ Error and Open Files Limit in Linux
- How to Increase the Max Open Files Limit in Linux?
- Increase the Maximum Number of Open File Descriptors per Service
- How to Set Max Open Files for Nginx and Apache?
- Change the Open File Limit for the Current User Session
‘Too Many Open Files’ Error and Open Files Limit in Linux
First of all, let’s see where the ‘too many open files’ errors appear. Most often it occurs on the servers with an installed Nginx /httpd web server or a database server running MySQL/MariaDB/PostgreSQL when reading a large number of log files. For example, when an Nginx exceeds the open files limit, you will see an error:
socket () failed (29: Too many open files) while connecting to upstream
Or:
HTTP: Accept error: accept tcp [::]:<port_number>: accept4: too many open files.
In Python apps:
OSError: [Errno 24] Too many open files.
Using this command, you can get the maximum number of file descriptors your system can open:
# cat /proc/sys/fs/file-max
To find out how many files are currently open, run:
# cat /proc/sys/fs/file-nr
7122 123 92312720
- 7122 — total number of open files
- 123– number of open files that are not currently in use
- 92312720– maximum number of files allowed to be opened
In Linux, you can configure max open files limits at several levels:
- OS kernel
- Service
- User
To display the current limit on the number of open files in the Linux kernel, run:
# sysctl fs.file-max
fs.file-max = 92233720
Let’s display the open files limit for one process of the current user:
# ulimit -n
By default, the number of files for one process of this is limited to 1024.
Let’s display the maximum number for one user (max user processes):
# ulimit –u
5041
Multiplying 1024 * 5041
gives us 5161984
– this is the maximum number of open files by all user processes.
There are two types of limits on the number of open files: Hard and Soft. Soft limits are advisory. If the number of open files has exceeded the hard limit, the user won’t be able to open new files until the previously opened ones are closed.
To view the current limits, use the ulimit command with the -S
(soft) or -H
(hard) option and the -n
(the maximum number of open file descriptors) option.
To display the soft limit, run this command:
# ulimit –Sn
To display the hard limit value:
# ulimit -Hn
How to Increase the Max Open Files Limit in Linux?
To allow all services to open a large number of files, you can change the limits in your Linux OS. To make new settings permanent and prevent their reset after a server or session restart, you must make changes to /etc/security/limits.conf. This file allows limiting the number of various system resources available to a user process. Use the following format:
username restriction_type restriction_name value
For example:
apache hard nofile 978160 apache soft nofile 978160
You can use *
instead of a username. This means that this open files limit will apply to all Linux users:
* hard nofile 97816 * soft nofile 97816
For example, you got a too many open files error for Nginx. Check how many files this user process is allowed to open:
$ sudo -u nginx bash -c 'ulimit -n'
1024
This is not enough for a high-load server. Add the following lines to /etc/security/limits.conf:
nginx hard nofile 50000 nginx soft nofile 50000
On older Linux kernels, the value of fs.file-max may be set to 10000. So check this value and increase it so that it is greater than the number in limits.conf:
# sysctl -w fs.file-max=500000
This will temporarily increase the open file limit. To make the new settings permanent, you need to add the following line to the /etc/sysctl.conf file:
fs.file-max = 500000
And apply it:
# sysctl -p
Check that the file /etc/pam.d/common-session (Debian/Ubuntu) or /etc/pam.d/login (CentOS/RedHat/Fedora) contains the line:
session required pam_limits.so
If not, add it to the end of the config file. This parameter allows applying open file limits after user authentication.
After making any changes, re-open the console, and check the max_open_files value:
# ulimit -n
50000
Increase the Maximum Number of Open File Descriptors per Service
You can increase the max open file descriptors for a specific service, rather than for the entire operating system. Let’s take apache as an example. Open the service settings using systemctl:
# systemctl edit httpd.service
Add the limits you want, e.g.:
[Service] LimitNOFILE=16000 LimitNOFILESoft=16000
After making the changes, update the service configuration, and restart it:
# systemctl daemon-reload
# systemctl restart httpd.service
To check if the values have changed, get the service PID:
# systemctl status httpd.service
For example, the service PID is 3724:
# cat /proc/3724/limits | grep "Max open files"
The value must be 16000.
Thus, you have changed Max open files value for a specific service.
How to Set Max Open Files for Nginx and Apache?
After you have increased the limit on the number of open files for a server, you also have to change the service configuration file. For example, specify/change the following directive value in the Nginx configuration file /etc/nginx/nginx.conf:
worker_rlimit_nofile 16000
The worker_rlimit_nofile directive sets the limit on the number of files open by a worker process ( RLIMIT_NOFILE ). Nginx needs file descriptors to return a static file from the cache for each client connection. The more users connect to your server and the more static files Nginx returns, the more file descriptors are used. The maximum number of handles is limited at the OS and/or service level. If the number of open files in Nginx is exceeded, a “socket() failed (24: Too many open files) while connecting to upstream error
” will occur.
[alert]When configuring Nginx on a high load 8-core server with worker_connections 8192, you need to specify 8192*2*8 (vCPU) = 131072 in worker_rlimit_nofile.
Then restart Nginx.
# nginx -t && service nginx -s reload
To see the number of open files for Nginx user processes:
# su nginx
# ulimit –Hn
# for pid in `pidof nginx`; do echo "$(< /proc/$pid/cmdline)"; egrep 'files|Limit' /proc/$pid/limits; echo "Currently open files: $(ls -1 /proc/$pid/fd | wc -l)"; echo; done
For Apache, you need to create a directory:
# mkdir /lib/systemd/system/httpd.service.d/
Then create the limit_nofile.conf file:
# nano /lib/systemd/system/httpd.service.d/limit_nofile.conf
Add to it:
[Service] LimitNOFILE=16000
Don’t forget to restart the httpd service.
Change the Open File Limit for the Current User Session
To change the maximum open file limits for your current user session, run this command:
# ulimit -n 3000
If you specify a value here greater than that specified in the hard limit, an error will appear:
-bash: ulimit: open files: cannot modify limit: Operation not permitted
After closing the session and opening a new one, the limits will return to the initial values specified in /etc/security/limits.conf.
In this article, we have learned how to solve the issue when the value of open file descriptors limit in Linux is too small, and looked at several options for changing these limits on the server.
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:
socket () failed (29: Too many open files) while connecting to upstream
To find the maximum number of file descriptors a system can open, run the following command:
# cat /proc/sys/fs/file-max
The open file limit for a current user is 1024. We can check it as follows:
# ulimit -n [root@server /]# cat /proc/sys/fs/file-max 97816 [root@server /]# ulimit -n 1024
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:
session required pam_limits.so
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:
systemctl edit httpd.service
Once the service settings is open, add the limits required. For example;
[Service] LimitNOFILE=16000 LimitNOFILESoft=16000
After making the changes, update the service configuration and restart it:
# systemctl daemon-reload # systemctl restart httpd.service
To ensure the values have changed, get the service PID:
# systemctl status httpd.service
For example, if the service PID is 3724:
# cat /proc/3724/limits | grep “Max open files”
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:
worker_rlimit_nofile 16000
While configuring Nginx on a highly loaded 8-core server with worker_connections 8192, we need to specify
8192*2*8 (vCPU) = 131072 in worker_rlimit_nofile
Then restart Nginx.
For apache, create a directory:
# mkdir /lib/systemd/system/httpd.service.d/
Then create the limit_nofile.conf file:
# nano /lib/systemd/system/httpd.service.d/limit_nofile.conf
Add to it:
[Service] LimitNOFILE=16000
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:
Finally, apply:
# sysctl -p [root@server /]# sysctl -p net.ipv4.ip_forward = 1 fs.file-max = 200000 [root@server /]# cat /proc/sys/fs/file-max 200000
[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.
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.
GET STARTED
var google_conversion_label = «owonCMyG5nEQ0aD71QM»;
If your Linux usage experience has led/exposed you to high-load Linux server environments, then there is a high chance you’ve crossed paths with the infamous “too many open files” error.
This Linux OS error simply implies that too many files (file descriptors) have been opened by a process and therefore no more files can be opened because the maximum open file limit has been met. Each system user or process in a Linux environment is assigned an open file limit value which is rather small.
This article will investigate the cause and cure of the “too many open files” error that is prominent in Linux operating system environments.
Understanding Linux File Descriptors
The entire hierarchy of a Linux operating system is file-attributed (be it the presentation of partitioned disk drives, network sockets, or regular/normal data). In Linux, once a file is open, it is identified by a non-negative integer called a file descriptor.
Open file descriptors are tabulated and linked to the process responsible for their existence. Whenever a new file is open, it is immediately appended as a new entry on the process’s table of open file descriptors.
For instance, consider the basic usage of the Linux cat command to open a simple text file. The open() system call is used to pass the filename as an argument before a file descriptor is assigned to it.
The cat command then takes advantage of the assigned file descriptor to interact with the file (display its content). When a user is done previewing the file, the close() system call is used to finally close the file.
At any given file operation instance, three file descriptors (all of them being open by default), are linked to a single file process. The three file descriptors are associated by their own unique notations and are as follows:
- 0 for stdin
- 1 for stdout
- 2 for stderr
Examining Linux Open File Descriptors
Under Linux file management, it is possible to associate various system agents and their assigned file descriptors (total number of file descriptors) to transparently account for used system resources.
Global Usage of File Descriptors
We can check the /proc/sys/fs/file-nr file’s first field with the following awk one-liner command:
$ awk '{print $1}' /proc/sys/fs/file-nr 12832
Per-Process Usage of File Descriptors
To check a process’s file descriptor usage, we first need to check the targeted process’s ID and then implement it in a lsof command. For instance, the per-process usage of the cat command’s file descriptors can be determined in the following manner:
First, run the ps aux command to determine the process id:
$ ps aux
Then implement the lsof command to determine the per-process file descriptors.
$ sudo lsof -p 3231
The NAME column points to the file descriptor’s exact file and the TYPE column points to the file type.
Check Linux File Descriptor Limits
It is the limit to the number of files a process is allowed to open at any given time. It can either be a soft limit or a hard limit. The soft limit is changeable (can only be lowered) by an unprivileged user but fully changeable by a privileged user. The hard limit is changeable by privileged users.
Per-Session Limit
To check the soft limit, use the -Sn
flag together with the ulimit command.
$ ulimit -Sn
To check the hard limit, use the -Hn
flag together with the ulimit command.
$ ulimit -Hn
Per-Process Limit
Here, we first retrieve a process’s PID and pass it as a variable in the procfs filesystem.
$ pid=3231 $ grep "Max open files" /proc/$pid/limits
The second and third columns point to the soft and hard limits respectfully.
Global Limit
Determines the total system-wide file descriptors for all processes combined.
$ cat /proc/sys/fs/file-max
Fixing “Too Many Open Files” Error in Linux
Now that we have understood the role of file descriptors, we can fix the error “too many open files errors” by increasing the file descriptors limit in Linux.
Temporarily (Per-Session)
This is a recommended approach. Here, we will use the ulimit -n command.
$ ulimit -n 4096 $ ulimit -Sn
We have changed the soft limit from 1024 to 4096.
To change the soft limit to the hard limit value of 1048576 or more, we will need privileged user access.
$ ulimit -n 1048577
Increase Per-User Limit
Here, we need to first open the /etc/security/limits.conf file.
$ sudo nano /etc/security/limits.conf
In reference to the below screen capture, you can append an entry like:
<domain> <type> <item> <value> * soft nofile 5000 * hard nofile 2000000
It is also advisable to specify the <item>
association with the file descriptor.
The changes above apply globally for all processes. You will need to re-logging or restart to your system for the changes to be effective.
Globally Increase Open File Limit
Open the /etc/sysctl.conf file.
$ sudo nano /etc/sysctl.conf
Append the following line with your desired file descriptor value.
fs.file-max = 2000000
Save the file and reload the configuration:
$ sudo sysctl -p
Restart your system or re-login.
We are now comfortable with handling the “Too many open files” error on our Linux systems.
When the “Too Many Open Files” error message is written to the logs, it indicates that all available file handles for the process have been used (this includes sockets as well).
In a majority of cases, this is the result of file handles being leaked by some part of the application. ulimit is a command in Unix/Linux which allows to set system limits for all properties.
Understanding Too Many Open Files Error in Linux
“Too many open files“ errors happen when a process needs to open more files than it is allowed by the operating system. This number is controlled by the maximum number of file descriptors the process has.
file-max is the maximum file descriptors (FD) enforced on a kernel level, which cannot be surpassed by all processes. The ulimit is enforced on a process level, which can be less than the file-max.
In some scenarios, even though the ulimit has been correctly configured, the total number of open files allowed for the entire system might be configured to a value less than the total number of files opened (by all processes).
If a process now tries to open file and we will hit the maximum number of files allowed for the system.
This error is generated when the open file limit for a user or system exceeds the default setting.
Check Too many open files in SYSTEM Wide settings in Linux
To see the settings for maximum open files for the OS level, use following command:
# cat /proc/sys/fs/file-max
To change the system wide maximum open files, as root edit the /etc/sysctl.conf and add the following to the end of the file:
fs.file-max = 495000
Then issue the following command to activate this change to the live system:
# sysctl -p
Check Too many open files Per USER Settings in Linux
We can see the setting for maximum open files for a user, as root issue the following commands:
# su – <user>
$ ulimit -n
The default setting for this is usually 1024. If more is needed for a specific user then as root modify it in the /etc/security/limits.conf file:
user – nofile 2048
Check Too many open files in systemd service on Linux
If we start a instance as a systemd service, we can specify limits within the [Service] section of its service file. The service file has a location like /etc/systemd/system/<process-name>.service.
we can set limits by using resource limit directives.
Specify the Recommended ulimit Settings, as in the following example:
[Service]
# Other directives omitted
# (file size)
LimitFSIZE=infinity
# (cpu time)
LimitCPU=infinity
# (virtual memory size)
LimitAS=infinity
# (locked-in-memory size)
LimitMEMLOCK=infinity
# (open files)
LimitNOFILE=64000
# (processes/threads)
LimitNPROC=64000
Quick Guide on how to fix Too Many Open Files in Linux
su to the user we want to check. we use root user as an example below.
su – root
Check max file number limit in Linux
#Check max limit in Linux
cat /proc/sys/fs/file-max
#Check number of global open file descriptors in use
sysctl fs.nr_open
#Check Hard Limit in Linux
ulimit -Hn
#Check Soft Limits in Linux
ulimit -Sn
#Check current number of open files being used by root
lsof -u root | awk ‘BEGIN { total = 0; } $4 ~ /^[0-9]/ { total += 1 } END { print total }’
#To increase roots limits
add/modifty the below to the limits.conf file
vi /etc/security/limits.conf
root soft nofile 2048
root hard nofile 4096
#To increase the system-wide limits
vi /etc/sysctl.conf
Add following:
fs.file-max = 3213254
#To make the changes take effect
Run:
sysctl -p
Open a new shell and verify that the changes have taken effect
the new values should be present by running
ulimit -Hn
ulimit -Sn
As the limits of root was changed, we will need to restart the application from a new shell window, or restart the system for the changes to take effect.
Is there a limit to the number of open files a user can have in Linux?
There is no definitive answer to this question as it can vary depending on the system and the configuration. However, the maximum number of open files that a process can have is typically limited to around 1024-2048 file descriptors. There are ways to increase this limit if necessary, but it’s best to try and stay within the recommended range whenever possible.