CentOS -Nginx优化 (6)

ab的使用

[root@localhostbin]# ab -n 10 -c 100 http://opslinux.com/

意思是这样的:

-n表示发送多少个请求,

-c表示一次发送多少个(实际上就是把-n分批发送, c次分发,每次n个请求),

后面跟地址,注意后的斜杠。

返回信息如下(红色部分为我的注释):

This isApacheBench, Version 2.0.40-dev <$Revision: 1.146 $> apache-2.0
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Copyright 2006 The Apache Software Foundation, http://www.apache.org/

Benchmarkinghttp://www.yi1.com.cm/ (be patient)…..done
Server Software:        Apache/2.2.4
Server Hostname:        
http://opslinux.com/
Server Port:           80

DocumentPath:          /
Document Length:        31848 bytes

ConcurrencyLevel:      10
Time taken for tests:   1.722254 seconds/*
测试持续时间*/
Complete requests:      10/*
完成请求数量*/
Failed requests:        0/*
失败请求数量*/
Write errors:           0
Total transferred:      323490 bytes/*
总流量*/
HTML transferred:       318480 bytes/*HTML
传输量*/
Requests per second:    5.81 [#/sec] (mean)/*
每秒事务数*/
Time per request:       1722.254 [ms] (mean)/*
平均响应时间*/
Time per request:       172.225 [ms] (mean,across all concurrent requests)/*
每个请求响应时间(平均)*/
Transfer rate:          182.90[Kbytes/sec] received/*
传输效率*/

ConnectionTimes (ms)
min  mean[+/-sd] median   max
Connect:      165  166  1.2    167     168
Processing:  1300 1418  91.5   1427    1554
Waiting:      803  925 92.9    929    1064
Total:       1465 1585  92.2  1595    1721

Percentage ofthe requests served within a certain time (ms)
50%   1595/*50%
的请求响应时间小于1595*/
66%   1620/*66%
的请求响应时间小于1620*/
75%   1668
80%   1706
90%   1721
95%   1721
98%   1721
99%   1721
100%   1721 (longest request)/*
最长响应时间1721*/


一,编译安装过程优化

在编译Nginx时,默认以debug模式进行,而在debug模式下会插入很多跟踪和ASSERT之类的信息,编译完成后,一个Nginx要有好几兆字节。在编译前取消Nginxdebug模式,编译完成后Nginx只有几百千字节,因此可以在编译之前,修改相关源码,取消debug模式,具体方法如下:Nginx源码文件被解压后,找到源码目录下的auto/cc/gcc文件,在其中找到如下1行, :注释掉或删除

# debug

CFLAGS=”$CFLAGS -g”


二,为特定的
CPU指定CPU类型编译优化

在编译Nginx时,默认的GCC编译参数是“-O”,要优化GCC编译,可以使用以下两个参数:

--with-cc-opt='-O3'

--with-cpu-opt=CPU  #为特定的 CPU编译,有效的值包括:pentium,pentiumpro, pentium3, pentium4, athlon, opteron, amd64, sparc32, sparc64, ppc64

要确定CPU类型,可以通过如下命令:

[root@localhost home]#cat /proc/cpuinfo | grep "modelname"


三,利用TCMalloc优化Nginx的性能  (CentOS必须是64位才可以使用) 

TCMalloc的全称为Thread-Caching Malloc,是谷歌开发的开源工具“google-perftools”中的一个成员。与标准的glibc库的malloc相比,TCMalloc库在内存分配效率和速度上要高很多,这在很大程度上提高了服务器在高并发情况下的性能,从而降低系统负载。下面简单介绍如何为Nginx添加TCMalloc库支持。要安装TCMalloc库,需要安装libunwind32位操作系统不需要安装)和google-perftools两个软件包,libunwind库为基于64CPU和操作系统的程序提供了基本函数调用链和函数调用寄存器功能。下面介绍利用TCMalloc优化Nginx的具体操作过程:

1.安装libunwind

可以从http://download.savannah.gnu.org/releases/libunwind下载相应的libunwind版本,这里下载的是libunwind-0.99-alpha.tar.gz,安装过程如下

[root@localhost home]#tar zxvf libunwind-0.99-alpha.tar.gz

[root@localhost home]# cd libunwind-0.99-alpha/

[root@localhost libunwind-0.99-alpha]#CFLAGS=-fPIC./configure

[root@localhost libunwind-0.99-alpha]#make CFLAGS=-fPIC

[root@localhost libunwind-0.99-alpha]#make CFLAGS=-fPICinstall

2.安装google-perftools

可以从http://google-perftools.googlecode.com下载相应的google-perftools版本,这里下载的是google-perftools-1.8.tar.gz,安装过程如下:

[root@localhost home]# tar zxvf google-perftools-1.8.tar.gz

[root@localhost home]# cd google-perftools-1.8/

[root@localhost google-perftools-1.8]# ./configure

[root@localhost google-perftools-1.8]# make && makeinstall

[root@localhost google-perftools-1.8]# echo"/usr/local/lib" > /etc/ld.so.conf.d/usr_local_lib.conf

[root@localhost google-perftools-1.8]# ldconfig

至此,google-perftools安装完成。

3.重新编译Nginx

为了使Nginx支持google-perftools,需要在安装过程中添加“–with-google_perftools_module”选项重新编译Nginx,安装代码如下:

[root@localhostnginx-0.7.65]#

./configure --user=www --group=www--prefix=/usr/local/nginx --with-http_stub_status_module --with-http_ssl_module--with-http_gzip_static_module --with-ipv6--with-google_perftools_module

 

[root@localhost nginx-0.7.65]#make

[root@localhost nginx-0.7.65]#make install

到这里Nginx安装完成。

4.google-perftools添加线程目录

创建一个线程目录,这里将文件放在/tmp/tcmalloc下,操作如下:

[root@localhost home]#mkdir /tmp/tcmalloc

[root@localhost home]#chmod 0777 /tmp/tcmalloc

5.修改Nginx主配置文件

修改nginx.conf文件,在pid这行的下面添加如下代码:

#pid       logs/nginx.pid;

google_perftools_profiles /tmp/tcmalloc;

接着,重启Nginx,完成google-perftools的加载。

6.验证运行状态

为了验证google-perftools已经正常加载,通过如下命令查看:

[root@ localhost home]# lsof -n | grep tcmalloc

nginx      2395nobody   9w  REG   8,8       0    1599440 /tmp/tcmalloc.2395

nginx      2396nobody   11w REG   8,8      0    1599443 /tmp/tcmalloc.2396

nginx      2397 nobody  13w REG  8,8        0   1599441  /tmp/tcmalloc.2397

nginx     2398nobody    15w REG  8,8    0    1599442 /tmp/tcmalloc.2398

由于在Nginx配置文件中,设置worker_processes的值为4,因此开启了4Nginx线程,每个线程会有一行记录。每个线程文件后面的数字值就是启动的NginxPID值。至此,利用TCMalloc优化Nginx的操作完成。


四,Nginx内核参数优化

内核参数的优化,主要是在Linux系统中针对Nginx应用而进行的系统内核参数优化,常见的优化参数值如下。

下面给出一个优化实例以供参考:

net.ipv4.tcp_max_tw_buckets = 6000

net.ipv4.ip_local_port_range = 1024 65000

net.ipv4.tcp_tw_recycle = 1

net.ipv4.tcp_tw_reuse = 1

net.ipv4.tcp_syncookies = 1

net.core.somaxconn = 262144

net.core.netdev_max_backlog = 262144

net.ipv4.tcp_max_orphans = 262144

net.ipv4.tcp_max_syn_backlog = 262144

net.ipv4.tcp_synack_retries = 1

net.ipv4.tcp_syn_retries = 1

net.ipv4.tcp_fin_timeout = 1

net.ipv4.tcp_keepalive_time = 30

将上面的内核参数值加入/etc/sysctl.conf文件中,然后执行如下命令使之生效:

[root@ localhost home]#/sbin/sysctl -p

下面是对实例中选项的含义进行介绍:

net.ipv4.tcp_max_tw_buckets参数用来设定timewait的数量,默认是180000,这里设为6000

net.ipv4.ip_local_port_range选项用来设定允许系统打开的端口范围。

net.ipv4.tcp_tw_recycle选项用于设置启用timewait快速回收。

net.ipv4.tcp_tw_reuse选项用于设置开启重用,允许将TIME-WAIT sockets重新用于新的TCP连接。

net.ipv4.tcp_syncookies选项用于设置开启SYN Cookies,当出现SYN等待队列溢出时,启用cookies进行处理。

net.core.somaxconn选项默认值是128这个参数用于调节系统同时发起的tcp连接数,在高并发的请求中,默认的值可能会导致链接超时或者重传,因此,需要结合并发请求数来调节此值。

net.core.netdev_max_backlog选项表示当每个网络接口接收数据包的速率比内核处理这些包的速率快时,允许发送到队列的数据包的最大数目。

net.ipv4.tcp_max_orphans选项用于设定系统中最多有多少个TCP套接字不被关联到任何一个用户文件句柄上。如果超过这个数字,孤立连接将立即被复位并打印出警告信息。这个限制只是为了防止简单的DoS攻击。不能过分依靠这个限制甚至人为减小这个值,更多的情况是增加这个值。

net.ipv4.tcp_max_syn_backlog选项用于记录那些尚未收到客户端确认信息的连接请求的最大值。对于有128MB内存的系统而言,此参数的默认值是1024,对小内存的系统则是128

net.ipv4.tcp_synack_retries参数的值决定了内核放弃连接之前发送SYN+ACK包的数量。

net.ipv4.tcp_syn_retries选项表示在内核放弃建立连接之前发送SYN包的数量。

net.ipv4.tcp_fin_timeout选项决定了套接字保持在FIN-WAIT-2状态的时间。默认值是60秒。正确设置这个值非常重要,有时候即使一个负载很小的Web服务器,也会出现因为大量的死套接字而产生内存溢出的风险。

net.ipv4.tcp_keepalive_time选项表示当keepalive启用的时候,TCP发送keepalive消息的频度。默认值是2(单位是小时)。

下面贴一个完整的内核优化设置:

vi /etc/sysctl.conf CentOS5.5中可以将所有内容清空直接替换为如下内容:

net.ipv4.ip_forward = 0

net.ipv4.conf.default.rp_filter = 1

net.ipv4.conf.default.accept_source_route = 0

kernel.sysrq = 0

kernel.core_uses_pid = 1

net.ipv4.tcp_syncookies = 1

kernel.msgmnb = 65536

kernel.msgmax = 65536

kernel.shmmax = 68719476736

kernel.shmall = 4294967296

net.ipv4.tcp_max_tw_buckets = 6000

net.ipv4.tcp_sack = 1

net.ipv4.tcp_window_scaling = 1

net.ipv4.tcp_rmem = 4096 87380 4194304

net.ipv4.tcp_wmem = 4096 16384 4194304

net.core.wmem_default = 8388608

net.core.rmem_default = 8388608

net.core.rmem_max = 16777216

net.core.wmem_max = 16777216

net.core.netdev_max_backlog = 262144

net.core.somaxconn = 262144

net.ipv4.tcp_max_orphans = 3276800

net.ipv4.tcp_max_syn_backlog = 262144

net.ipv4.tcp_timestamps = 0

net.ipv4.tcp_synack_retries = 1

net.ipv4.tcp_syn_retries = 1

net.ipv4.tcp_tw_recycle = 1

net.ipv4.tcp_tw_reuse = 1

net.ipv4.tcp_mem = 94500000 915000000 927000000

net.ipv4.tcp_fin_timeout = 1

net.ipv4.tcp_keepalive_time = 30

net.ipv4.ip_local_port_range = 1024 65000


五,简单配置文件

下面是一个简单的nginx 配置文件:

user www www;

worker_processes 8;

worker_cpu_affinity 00000001 00000010 00000100 0000100000010000 00100000

01000000;

error_log /www/log/nginx_error.log crit;

pid /usr/local/nginx/nginx.pid;

worker_rlimit_nofile 204800;

events

{

use epoll;

worker_connections 204800;

}

http

{

include mime.types;

default_type application/octet-stream;

charset utf-8;

server_names_hash_bucket_size 128;

client_header_buffer_size 2k;

large_client_header_buffers 4 4k;

client_max_body_size 8m;

sendfile on;

tcp_nopush on;

keepalive_timeout 60;

fastcgi_cache_path /usr/local/nginx/fastcgi_cache levels=1:2

keys_zone=TEST:10m

inactive=5m;

fastcgi_connect_timeout 300;

fastcgi_send_timeout 300;

fastcgi_read_timeout 300;

fastcgi_buffer_size 4k;

fastcgi_buffers 8 4k;

fastcgi_busy_buffers_size 8k;

fastcgi_temp_file_write_size 8k;

fastcgi_cache TEST;

fastcgi_cache_valid 200 302 1h;

fastcgi_cache_valid 301 1d;

fastcgi_cache_valid any 1m;

fastcgi_cache_min_uses 1;

fastcgi_cache_use_stale error timeout invalid_headerhttp_500;

open_file_cache max=204800 inactive=20s;

open_file_cache_min_uses 1;

open_file_cache_valid 30s;

tcp_nodelay on;

gzip on;

gzip_min_length 1k;

gzip_buffers 4 16k;

gzip_http_version 1.0;

gzip_comp_level 2;

gzip_types text/plain application/x-javascript text/cssapplication/xml;

gzip_vary on;

server

{

listen 8080;

server_name backup.aiju.com;

index index.php index.htm;

root /www/html/;

location /status

{

stub_status on;

}

location ~ .*\.(php|php5)?$

{

fastcgi_pass 127.0.0.1:9000;

fastcgi_index index.php;

include fcgi.conf;

}

location ~ .*\.(gif|jpg|jpeg|png|bmp|swf|js|css)$

{

expires 30d;

}

log_format access ‘$remote_addr — $remote_user [$time_local]“$request” ‘

‘$status $body_bytes_sent “$http_referer” ‘

‘”$http_user_agent” $http_x_forwarded_for’;

access_log /www/log/access.log access;

}

}


六,关于FastCGI的几个指令:

fastcgi_cache_path/usr/local/nginx/fastcgi_cache levels=1:2 keys_zone=TEST:10minactive=5m;

这个指令为FastCGI 缓存指定一个路径,目录结构等级,关键字区域存储时间和非活动删除时间。

fastcgi_connect_timeout 300;

指定连接到后端FastCGI 的超时时间。

fastcgi_send_timeout 300;

FastCGI 传送请求的超时时间,这个值是指已经完成两次握手后向FastCGI传送请求的超时时间。

fastcgi_read_timeout 300;

接收FastCGI 应答的超时时间,这个值是指已经完成两次握手后接收FastCGI应答的超时时间。

fastcgi_buffer_size 4k;

指定读取FastCGI 应答第一部分需要用多大的缓冲区,一般第一部分应答不会超过1k,由于页面大小为4k,所以这里设置为4k

fastcgi_buffers 8 4k;

指定本地需要用多少和多大的缓冲区来缓冲FastCGI的应答。

fastcgi_busy_buffers_size 8k;

这个指令我也不知道是做什么用,只知道默认值是fastcgi_buffers的两倍。

fastcgi_temp_file_write_size 8k;

在写入fastcgi_temp_path时将用多大的数据块,默认值是fastcgi_buffers的两倍。

fastcgi_cache TEST

开启FastCGI 缓存并且为其制定一个名称。个人感觉开启缓存非常有用,可以有效降低CPU负载,并且防止502 错误。

fastcgi_cache_valid 200 302 1h;fastcgi_cache_valid 301 1d; fastcgi_cache_valid any 1m;

为指定的应答代码指定缓存时间,如上例中将200302应答缓存一小时,301应答缓存1 天,其他为1 分钟。

fastcgi_cache_min_uses 1;

缓存在fastcgi_cache_path指令inactive 参数值时间内的最少使用次数,如上例,如果在5分钟内某文件1 次也没有被使用,那么这个文件将被移除。

fastcgi_cache_use_stale error timeoutinvalid_header http_500;

不知道这个参数的作用,猜想应该是让nginx知道哪些类型的缓存是没用的。以上为nginxFastCGI 相关参数,另外,FastCGI 自身也有一些配置需要进行优化,如果你使用php-fpm来管理FastCGI,可以修改配置文件中的以下值:

再来优化PHP-FPM,打开/usr/local/php/etc/php-fpm.conf,这个文件和PHP的语法很相似,凡是需要激活的配置,直接删掉前面的分号(;)即可:

1.        [global]  

2.         

3.       pid = run/php-fpm.pid  

4.         

5.       process_control_timeout=5  

6.         

7.       [www]  

8.         

9.       listen.allowed_clients = 127.0.0.1  

10.       

11.     user=www-data  

12.       

13.     group=www-data  

14.       

15.     pm=dynamic  

16.       

17.     pm.max_children=20(这个配置决定了php-fpm的总进程数,内存小的少设点)  

18.       

19.     pm.max_requests=10000(并发数越大,此请求数应越大)  

20.       

21.     pm.start_servers =10(初始php-fpm进程数)  

22.       

23.     emergency_restart_threshold = 60  

24.       

25.     emergency_restart_interval = 60s  

上边这两个,表示在emergency_restart_interval所设值内出现SIGSEGV或者SIGBUS错误的php-cgi进程数如果超过emergency_restart_threshold个,php-fpm就会优雅重启。这两个选项一般保持默认值


七,ulimit关于系统连接数的优化

linux 默认值 open files max user processes 1024

#ulimit -n

1024

#ulimit –u

1024

问题描述:说明 server只允许同时打开 1024个文件,处理 1024个用户进程

使用ulimit -a 可以查看当前系统的所有限制值,使用ulimit -n可以查看当前的最大打开文件数。

新装的linux 默认只有1024 ,当作负载较大的服务器时,很容易遇到error: too many open files。因此,需要将其改大。

解决方法:

使用 ulimit –n 65535可即时修改,但重启后就无效了。(注ulimit -SHn 65535等效 ulimit -n 65535-S soft -Hhard)

修改方式

有如下三种修改方式:

1.     /etc/rc.local中增加一行 ulimit -SHn 65535

2.     /etc/profile中增加一行 ulimit -SHn 65535

3.     /etc/security/limits.conf最后增加:

4.  * soft nofile 65535

5.  * hard nofile 65535

6.  * soft nproc 65535

7.  * hard nproc 65535

具体使用哪种,在 CentOS中使用第1 种方式无效果,使用第3 种方式有效果,而在Debian 中使用第2 种有效果

# ulimit -n

65535

# ulimit -u

65535

备注:ulimit 命令本身就有分软硬设置,加-H 就是硬,加-S 就是软默认显示的是软限制

soft 限制指的是当前系统生效的设置值。 hard限制值可以被普通用户降低。但是不能增加。 soft限制不能设置的比 hard限制更高。只有 root用户才能够增加 hard限制值。

==========================================优化后并发效果明显====================================


[root@localhost www]# ab -n 100000 -c 1000 http://127.0.0.1/
This is ApacheBench, Version 2.0.40-dev <$Revision: 1.146 $> apache-2.0
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Copyright 2006 The Apache Software Foundation, http://www.apache.org/


Benchmarking 127.0.0.1 (be patient)
Completed 10000 requests
Completed 20000 requests
Completed 30000 requests
Completed 40000 requests
Completed 50000 requests
Completed 60000 requests
Completed 70000 requests
Completed 80000 requests
Completed 90000 requests
Finished 100000 requests




Server Software:        nginx/1.0.15
Server Hostname:        127.0.0.1
Server Port:            80


Document Path:          /
Document Length:        151 bytes


Concurrency Level:      1000
Time taken for tests:   29.212222 seconds
Complete requests:      100000
Failed requests:        0
Write errors:           0
Total transferred:      37700000 bytes
HTML transferred:       15100000 bytes
Requests per second:    3423.22 [#/sec] (mean)
Time per request:       292.122 [ms] (mean)
Time per request:       0.292 [ms] (mean, across all concurrent requests)
Transfer rate:          1260.29 [Kbytes/sec] received


Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0  140  81.0    140     317
Processing:    85  150  11.4    150     201
Waiting:        0   66  38.4     66     136
Total:        131  290  90.2    290     480


Percentage of the requests served within a certain time (ms)
  50%    290
  66%    340
  75%    368
  80%    384
  90%    416
  95%    432
  98%    441
  99%    446
 100%    480 (longest request)
[root@localhost www]#

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值