新安裝的linux系統允許每個程序的最大打開文件數默認是1024,可以通過ulimit -n命令來查看,查看全部限制,則可以使用命令ulimit -a
[root@test ~]# ulimit -a core file size (blocks, -c) 0 data seg size (kbytes, -d) unlimited scheduling priority (-e) 0 file size (blocks, -f) unlimited pending signals (-i) 63399 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) 63399 virtual memory (kbytes, -v) unlimited file locks (-x) unlimited
修改這個值,可以有這些方法
系統全局參數file-max
cat /proc/sys/fs/file-max 1613096
系統級別的限制
如果是系統服務
編輯服務配置文件:/usr/lib/systemd/system/SERVICE_NAME.service,在[Service]段添加行:LimitNOFILE=65535,下面是nginx的示例:
vim nginx.service [Unit] Description=nginx - high performance web server Documentation=http://nginx.org/en/docs/ After=network-online.target remote-fs.target nss-lookup.target Wants=network-online.target [Service] Type=forking PIDFile=/opt/web_engine/nginx/run/nginx.pid ExecStartPre=/opt/web_engine/nginx/sbin/nginx -t -c /opt/web_engine/nginx/conf/nginx.conf ExecStart=/opt/web_engine/nginx/sbin/nginx -c /opt/web_engine/nginx/conf/nginx.conf ExecReload=/bin/kill -s HUP $MAINPID ExecStop=/bin/kill -s TERM $MAINPID LimitNOFILE=65535 [Install] WantedBy=multi-user.target
運行systemctl daemon-reload讓配置文件激活,再重啟服務,即可讓配置生效
查看配置是否生效:ps -ef|grep nginx 得到nginx主進程的PID
cat /proc/$PID/limits 如果看到Max open files 65535 65535 files 則說明配置已生效
臨時修改,重啟后失效,不對運行中程序生效
運行命令:ulimit -HSn 65535 該命令也等同於ulimit -n 65535
H為硬限制,S為軟限制,需要注意的是,退出登錄后,將失效
永久修改,需要重啟系統
一般方式:
vim /etc/security/limits.conf 添加
* soft nofile 65535
* hard nofile 65535
* hard nofile 65535
*代表用戶,全部用戶或用戶組
#MySQL env mysql soft nproc 2047 mysql hard nproc 16384 mysql soft nofile 1024 mysql hard nofile 65536 mysql soft stack 10240
上面的nproc是允許創建的子進程數目,不能過大,防止accidental fork bombs,一般4096比較合適
高級一點的做法:
將配置寫到/etc/security/limits.d/nofile.conf 這種不直接寫到系統limits文件中,當limits需要升級時,不會丟失配置
另外一種做法:
在系統啟動過程中,執行一次ulimit -SHn 65533,比如可以寫到/etc/rc.local中,或者/etc/profile中等
動態修改運行中程序的值
不安全的作法,但是在不可中止運行中程序的時候,會很管用
直接修改文件:/proc/$PID/limits 的這一行Max open files 65535 65535 files
命令行操作:
prlimit --pid 24340 --nofile=65535:65535
