通常我們在設置某個進程可打開最大文件句柄數的時候都會去找/etc/security/limits.conf
這個文件,在底部添加類似如下的設置
* soft nofile 65535 * hard nofile 65535 * soft nproc 65535 * hard nproc 65535
但是有時候你會發現設置並沒有生效,比如mysql服務,明明配置文件設置了max_connections=5000或者其他數值,但是
進入mysql后,通過show variables like '%connections%';你會發現這里的最大可打開連接數還是受限
root@server 11:54: [(none)]> root@server 11:54: [(none)]> root@server 11:54: [(none)]> show variables like '%connections%'; +------------------------+-------+ | Variable_name | Value | +------------------------+-------+ | max_connections | 214 | | max_user_connections | 0 | | mysqlx_max_connections | 100 | +------------------------+-------+ 3 rows in set (0.02 sec) root@server 11:54: [(none)]> exit Bye
同時你通過cat /proc/mysql進程id/limits會發現這里的限制也依然是
[root@local-huajing /root]# cat /proc/1823/limits Limit Soft Limit Hard Limit Units Max cpu time unlimited unlimited seconds Max file size unlimited unlimited bytes Max data size unlimited unlimited bytes Max stack size 8388608 unlimited bytes Max core file size 0 unlimited bytes Max resident set unlimited unlimited bytes Max processes 65535 65535 processes Max open files 1024 4096 files Max locked memory 65536 65536 bytes Max address space unlimited unlimited bytes Max file locks unlimited unlimited locks Max pending signals 15505 15505 signals Max msgqueue size 819200 819200 bytes Max nice priority 0 0 Max realtime priority 0 0 Max realtime timeout unlimited unlimited us
你會發現mysql進程這里分別是1024和4096,也並未被/etc/security/limits.conf 的設置影響。
仔細看/etc/security/limits.conf 文件頂部的說明,你會發現有了相關說明,
[root@local-huajing /root]# cat /etc/security/limits.conf # /etc/security/limits.conf # #This file sets the resource limits for the users logged in via PAM. #It does not affect resource limits of the system services. # #Also note that configuration files in /etc/security/limits.d directory, #which are read in alphabetical order, override the settings in this #file in case the domain is the same or more specific. #That means for example that setting a limit for wildcard domain here #can be overriden with a wildcard setting in a config file in the #subdirectory, but a user specific setting here can be overriden only #with a user specific setting in the subdirectory. # #Each line describes a limit for a user in the form: # #<domain> <type> <item> <value>
可以發現第二行紅字說明,此設置對system services不生效,只對通過PAM登錄的用戶生效,也就是說我們使用systemd管理的
服務進程是不受這里影響的,那么受什么影響呢,就是/etc/systemd/system.conf 及/etc/systemd/user.conf文件,有什么區別呢
取決你systemd服務本身運行在什么狀態,是系統實例還是用戶實例,通常情況下是運行在系統實例。如圖:就代表運行以系統實例狀態
在運行,那么怎么以用戶實例運行呢,需要把--system 換成--user即可。不過通常情況下都是系統實例狀態。

那么回到剛才那2個配置文件,以什么狀態運行,你就去哪里修改配置文件內容即可,繼續回到字上面的mysql的問題,我的mysqld服務就是用systemd管理的,並在運行為系統實例
那么我就需要修改etc/systemd/system.conf 里面的最大可打開文件句柄數即可。如下圖:
取消前面的注釋,並設置為65535,並重啟服務器。

重啟服務器之后,你再去看mysql進程的可打開最大文件,你會發現均變為了65535,同時登錄mysql查看max_connection由原來的214也變為5000了。
當然網上也有直接在mysqld的service文件里在service段直接添加LimitNOFILE=65535配置解決,原理都是一樣的。二者皆可。

PS:如果你的mysql進程是通過普通的命令行啟動的,而不是systemctl,那么是可以讀取/etc/security/limits.conf里面的配置的。
