修改Apache的Max open files限制

相信绝大多数人,都是直接对 /etc/security/limits.conf  文件进行的修改,添加类似下面的两行:

*     soft         nofile           10240
*     hard       nofile           10240

这样也能达到效果。但是经验告诉我,能在局部修改,就不要动全局——因为我们不好评估全局会对哪些应用造成影响(就修改nofile参数一事来说,目前还没有发现修改全局对系统的明显影响,但是理论上可以肯定,将全局的限制放宽,意味着使系统容易受到“资源耗尽”类的攻击,然而在我的工作经历中,还没有遇到一例类似事故发生过),所以我建议将这些局部性的修改放到各自的启动脚本里。

在apachectl脚本里,有这样的语句:

#
# Set this variable to a command that increases the maximum
# number of file descriptors allowed per child process. This is
# critical for configurations that use many file descriptors,
# such as mass vhosting, or a multithreaded server.
ULIMIT_MAX_FILES=”ulimit -S -n `ulimit -H -n`”
# ——————–                              ——————–
# ||||||||||||||||||||   END CONFIGURATION SECTION  ||||||||||||||||||||

# Set the maximum number of file descriptors allowed per child process.
if [ "x$ULIMIT_MAX_FILES" != "x" ] ; then
    $ULIMIT_MAX_FILES
fi

所以,我推荐直接修改apachectl,在ULIMIT_MAX_FILES=”ulimit -S -n `ulimit -H -n`” 之前,设定nofile的“硬限制”,如下:

# number of file descriptors allowed per child process. This is
# critical for configurations that use many file descriptors,
# such as mass vhosting, or a multithreaded server.
ulimit -H -n 5000
ULIMIT_MAX_FILES=”ulimit -S -n `ulimit -H -n`”
# ——————–                              ——————–
# ||||||||||||||||||||   END CONFIGURATION SECTION  ||||||||||||||||||||

# Set the maximum number of file descriptors allowed per child process.
if [ "x$ULIMIT_MAX_FILES" != "x" ] ; then
    $ULIMIT_MAX_FILES
fi

这样修改的好处在于,只有Apache的“nofile”受到影响,不影响其它。
原公司的所有应用的管理脚本中(apachectl、nginxctl),都进行了修改,并且使用”isystem”(自己写的一套脚本、小程序的集合)进行统一管理,以至于到后来,我几乎已经忘掉了这些事情,但是系统仍然运行良好,没有再出过 “too many open files” 的问题。

注意:修改过nofile的hard限制以后,需要先stop,再start,httpd进程的限制才能使用新改的参数。

查看当前运行中的进程的limit信息,可以利用/proc(当前Linux内存为2.6),比如apache的一个进程号是10232:

cat /proc/10232/limits

On this day..

Tags: , , , , , ,

Leave a comment