博客:http://lijinhuan.blog.51cto.com/

微博:http://weibo.com/lijinhuanexperience

代码:https://github.com/lijinhuan



一、模块管理

1、nginx是模块化结构,但是它和apache不一样,它的模块不能动态加载或者卸载。

  它是一种静态模块系统,如果想要卸载或者安装新的模块,必须重新编译指定

2、编译时./configure --help 查看所有模块;--without--xx表示默认安装,--with--xx可选安装

  选择模块安装方式,指定即可,./configure --with-http_stub_status_module --with-http_ssl_module --with-http_gzip_static_module --with-ipv6 

3、使用第三方模块,使用--add-module指定

  如:--add-module=../ngx_lua-0.9.12 --add-module=../ngx_lua_upstream-0.02



二、进程管理

1、nginx分为master和single两种模式运行;single顾名思义就是单进程方式运行,master是一个master进程加n

  个worker进程的方式运行。single模式容错能力差,生产环境不能使用,一般使用master方式运行

2、master进程只能有一个,主要负责全局的初始化和管理worker进程。master可以处理很多信号,例如WINCH,从容关闭

   工作进程,HUP重新装载配置等

3、如果你有多个cpu,可以在worker_processes设置和cpu核数一致,不过一般可以设置少一个,因为系统本身也需要cpu处理

4、针对nginx的系统优化

(1)关闭不必要的服务

(2)优化写磁盘操作:nginx每访问完一个文件之后,会对文件的修改时间进行修改,高并发时,对磁盘影响很大

需要关闭该功能,如:/dev/sdb1 /data/ext3 defaults 0 0

(3)资源限制优化:ulimit -a 查看

pending signals                 (-i) 7894

max locked memory       (kbytes, -l) 64

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

max user processes              (-u) 7894

主要是open files 和max user processes 参数,1024和7891在高并发系统中是远远不够的。

可以修改cat /etc/security/limits.conf 

如:# End of file

*    -     nofile    512000

(4)优化内核tcp选项:

/etc/sysctl.conf是一个允许你改变正在运行中的Linux系统的接口。它包含一些TCP/IP堆栈和虚拟内存系统的高级选项,可用来控制Linux网络配置,由于/proc/sys/net目录内容的临时性,建议把TCPIP参数的修改添加到/etc/sysctl.conf文件, 然后保存文件,使用命令“/sbin/sysctl –p”使之立即生效。

#为0,表示禁止数据包转发,1表示允许

net.ipv4.ip_forward = 0

#开启IP源地址验证,防止IP地址欺骗,在任何情况下都应开启,默认关闭

net.ipv4.conf.default.rp_filter = 1

# 禁用icmp源路由选项

net.ipv4.conf.default.accept_source_route = 0

#使用sysrq组合键是了解系统目前运行情况,为安全起见设为0关闭 

kernel.sysrq = 0

#控制core文件的文件名是否添加pid作为扩展 

kernel.core_uses_pid = 1

#表示开启SYN Cookies。当出现SYN等待队列溢出时,启用cookies来处理,可防范少量SYN***,默认为0,表示关闭;

net.ipv4.tcp_syncookies = 1

#即队列存放消息的总字节数。

kernel.msgmnb = 65536

#即一个消息的字节大小。目前扩展值为8k,平台一个交易消息为4个字节,不会超过限制。

kernel.msgmax = 65536

#指的是单个共享内存段的最大尺寸,

kernel.shmmax = 68719476736

#所有内存大小

kernel.shmall = 4294967296

net.ipv4.tcp_max_syn_backlog = 4096

net.ipv4.tcp_fin_timeout = 15

net.ipv4.tcp_keepalive_time = 1800

net.ipv4.icmp_echo_ignore_broadcasts = 1

net.ipv4.icmp_ignore_bogus_error_responses = 1

net.ipv4.tcp_retrans_collapse = 0

vm.swappiness = 1

net.ipv4.tcp_rmem = 4096 87380 524288

net.core.rmem_max = 1048576

net.ipv4.tcp_wmem = 4096 65536 524288

net.core.wmem_max = 1048576

net.core.somaxconn = 10240

net.ipv4.tcp_tw_reuse = 1

net.ipv4.tcp_tw_recycle = 1

net.ipv4.ip_local_port_range = 1025 65000

net.ipv4.tcp_max_tw_buckets = 8192

net.ipv4.tcp_timestamps = 0

vm.oom_kill_allocating_task = 0

vm.overcommit_memory = 0

5、nginx服务器优化

(1)尽量关闭访问日志

(2)使用epoll

(3)配置优化参考:http://down.chinaz.com/server/201202/1615_1.htm