ngx_http_fastcgi_module fastcgi模块
http://nginx.org/en/docs/http/ngx_http_fastcgi_module.html
The ngx_http_fastcgi_module module allowspassing requests to a FastCGI server.
配置示例:
location / {
fastcgi_pass localhost:9000;
fastcgi_indexindex.php;
fastcgi_param SCRIPT_FILENAME /home/www/scripts/php$fastcgi_script_name;
fastcgi_param QUERY_STRING $query_string;
fastcgi_param REQUEST_METHOD $request_method;
fastcgi_param CONTENT_TYPE $content_type;
fastcgi_param CONTENT_LENGTH $content_length;
}
1、配置在PHP中使用fastcgi模块
编辑default.conf,开启如下内容:
location ~ \.php$ {
root html;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
include fastcgi_params;
}
编辑fastcgi_params,修改为如下内容
fastcgi_param QUERY_STRING $query_string;
fastcgi_param REQUEST_METHOD $request_method;
fastcgi_param CONTENT_TYPE $content_type;
fastcgi_param CONTENT_LENGTH $content_length;
fastcgi_param SCRIPT_NAME $fastcgi_script_name;
fastcgi_param REQUEST_URI $request_uri;
fastcgi_param DOCUMENT_URI $document_uri;
fastcgi_param DOCUMENT_ROOT $document_root;
fastcgi_param SERVER_PROTOCOL $server_protocol;
fastcgi_param HTTPS $https if_not_empty;
fastcgi_param GATEWAY_INTERFACE CGI/1.1;
fastcgi_param SERVER_SOFTWARE nginx/$nginx_version;
fastcgi_param REMOTE_ADDR $remote_addr;
fastcgi_param REMOTE_PORT $remote_port;
fastcgi_param SERVER_ADDR $server_addr;
fastcgi_param SERVER_PORT $server_port;
fastcgi_param SERVER_NAME $server_name;
# PHP only,required if PHP was built with --enable-force-cgi-redirect
fastcgi_param REDIRECT_STATUS 200;
案例1、安装php-fpm并使用fastcgi模块
[root@www conf.d]# yum install php-fpm
[root@www conf.d]# rpm -ql | grep php-fpm
rpm: noarguments given for query
[root@www conf.d]# rpm -ql php-fpm
/etc/logrotate.d/php-fpm
/etc/php-fpm.conf
/etc/php-fpm.d
/etc/php-fpm.d/www.conf
/etc/rc.d/init.d/php-fpm
/etc/sysconfig/php-fpm
/usr/sbin/php-fpm
/usr/share/doc/php-fpm-5.3.3
/usr/share/doc/php-fpm-5.3.3/LICENSE
/usr/share/doc/php-fpm-5.3.3/php-fpm.conf.default
/usr/share/fpm/status.html
/usr/share/man/man8/php-fpm.8.gz
/var/log/php-fpm
/var/run/php-fpm
php-fpm参数
[root@www nginx]# /usr/sbin/php-fpm -h
Usage: php-fpm [-n] [-e] [-h] [-i] [-m] [-v] [-t] [-p<prefix>] [-g <pid>] [-c <file>] [-d foo[=bar]] [-y<file>] [-D] [-F]
-c<path>|<file> Look for php.ini file in this directory
-n No php.ini file will be used
-dfoo[=bar] Define INI entry foo withvalue 'bar'
-e Generate extended informationfor debugger/profiler
-h This help
-i PHP information
-m Show compiled in modules
-v Version number
-p, --prefix<dir>
Specify alternative prefix path to FastCGI process manager (default:/usr).
-g, --pid<file>
Specify the PID file location.
-y,--fpm-config <file>
Specify alternative path to FastCGI process manager config file.
-t,--test Test FPM configuration andexit
-D,--daemonize force to run in background,and ignore daemonize option from config file
-F,--nodaemonize
force to stay in foreground, and ignore daemonize option from configfile
-R,--allow-to-run-as-root
Allow pool to run as root (disabled by default)
在后台启动php-fpm
[root@www nginx]# /usr/sbin/php-fpm -D
[root@www ~]# ss -tnlup | grep 9000
tcp 0 128 127.0.0.1:9000 *:* users:(("php-fpm",10512,7),("php-fpm",10513,0),("php-fpm",10514,0),("php-fpm",10515,0),("php-fpm",10516,0),("php-fpm",10517,0))
[root@wwwnginx]# vim conf.d/default.conf
……..
location / {
root /usr/share/nginx/html;
# proxy_pass http://192.168.88.130/;
index index.php index.html index.htm;
}
......
location ~ \.php$ {
root /usr/share/nginx/html
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
include fastcgi_params;
}
[root@wwwnginx]# vi fastcgi_params
fastcgi_param GATEWAY_INTERFACE CGI/1.1;
fastcgi_param SERVER_SOFTWARE nginx;
fastcgi_param QUERY_STRING $query_string;
fastcgi_param REQUEST_METHOD $request_method;
fastcgi_param CONTENT_TYPE $content_type;
fastcgi_param CONTENT_LENGTH $content_length;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param SCRIPT_NAME $fastcgi_script_name;
fastcgi_param REQUEST_URI $request_uri;
fastcgi_param DOCUMENT_URI $document_uri;
fastcgi_param DOCUMENT_ROOT $document_root;
fastcgi_param SERVER_PROTOCOL $server_protocol;
fastcgi_param REMOTE_ADDR $remote_addr;
fastcgi_param REMOTE_PORT $remote_port;
fastcgi_param SERVER_ADDR $server_addr;
fastcgi_param SERVER_PORT $server_port;
fastcgi_param SERVER_NAME $server_name;
# PHP only,required if PHP was built with --enable-force-cgi-redirect
#fastcgi_param REDIRECT_STATUS 200;
[root@wwwnginx]# cd /usr/share/nginx/html
[root@www html]#vim index.php
<?php
phpinfo();
?>
[root@www html]# service nginx configtest
nginx: theconfiguration file /etc/nginx/nginx.conf syntax is ok
nginx:configuration file /etc/nginx/nginx.conf test is successful
[root@www html]#service nginx restart
停止 nginx:[确定]
正在启动 nginx:[确定]
[root@www html]#
访问http://192.168.88.131:8080/index.php,可以看到打开PHP主页面
案例2、PHP添加mysql模块、安装mysql服务器并使用fascgi测试。
[root@www nginx]# yum install php-mysql
[root@www nginx]# rpm -ql php-mysql
/etc/php.d/mysql.ini
/etc/php.d/mysqli.ini
/etc/php.d/pdo_mysql.ini
/usr/lib64/php/modules/mysql.so
/usr/lib64/php/modules/mysqli.so
/usr/lib64/php/modules/pdo_mysql.so
[root@www html]#service php-fpm restart
停止 php-fpm:[确定]
正在启动 php-fpm:[确定]
[root@www html]#
刷新页面,可以看到打开PHP主页面出现MySQL信息:
mysql
MySQL Support enabled
ActivePersistent Links 0
Active Links 0
Client APIversion 5.1.73
MYSQL_MODULE_TYPE external
MYSQL_SOCKET /var/lib/mysql/mysql.sock
MYSQL_INCLUDE -I/usr/include/mysql
MYSQL_LIBS -L/usr/lib64/mysql -lmysqlclient
安装mysql服务器
[root@wwwnginx]# yum install mysql-server
编辑测试页面:
[root@wwwnginx]# vim /usr/share/nginx/html/index.php
<?php
$conn =mysql_connect('127.0.0.1','root','');
if ($conn)
echo success;
else
echo fail;
mysql_close();
?>
[root@wwwnginx]# service mysqld start
初始化 MySQL 数据库: Installing MySQL system tables...
OK
Filling helptables...
OK
To start mysqldat boot time you have to copy
support-files/mysql.serverto the right place for your system
PLEASE REMEMBERTO SET A PASSWORD FOR THE MySQL root USER !
To do so, startthe server, then issue the following commands:
/usr/bin/mysqladmin-u root password 'new-password'
/usr/bin/mysqladmin-u root -h www.field.com password 'new-password'
Alternativelyyou can run:
/usr/bin/mysql_secure_installation
which will alsogive you the option of removing the test
databases andanonymous user created by default. Thisis
stronglyrecommended for production servers.
See the manualfor more instructions.
You can startthe MySQL daemon with:
cd /usr ;/usr/bin/mysqld_safe &
You can test theMySQL daemon with mysql-test-run.pl
cd/usr/mysql-test ; perl mysql-test-run.pl
Please reportany problems with the /usr/bin/mysqlbug script!
[确定]
正在启动 mysqld: [确定]
[root@www html]#ss -tnlup |grep mysqld
tcp 0 50 *:3306 *:* users:(("mysqld",11007,11))
[root@www html]#
访问http://www.field.com:8080/index.php,可以看到【success】
[root@wwwnginx]# service mysqld stop
停止 mysqld: [确定]
[root@wwwnginx]#
访问http://www.field.com:8080/index.php,可以看到【fail】
2、fastcgi_cache 使用
Syntax: fastcgi_cachezone | off;
Default:
fastcgi_cache off;
Context: http,server, location
1).编辑nginx.conf,添加如下内容:
fastcgi_cache_path /cache/fastcgi/ levels=1:2 keys_zone=fcgicache:10minactive=3m max_size=1g;
fastcgi_cache_path:定义缓存目录,可以设置目录层级,缓存文件路径定义levels=1:2,一级子目录一个字符表示,2级子目录两个字符表示
总共有62*62*62个文件,即1:2会生成16*256个子目录,fcgicache是这个缓存空间的名字,10m表示该zone使用10m内存
(Nginx直接放内存,提高访问速度),inactive表示默认失效时间,max_size表示最多用多少硬盘空间。
2).编辑default.conf,添加如下内容:
location ~ \.php$ {
fastcgi_cache fcgicache;
fastcgi_cache_key $host$request_uri;
fastcgi_cache_min_uses 1;
fastcgi_cache_use_stale error timeout invalid_header http_500;
#fastcgi_cache off;
fastcgi_cache_valid 200 10m;
fastcgi_cache_valid 302 3m;
fastcgi_cache_valid any 1m;
}
#fastcgi_cache_valid:定义哪些http头要使用缓存
#fastcgi_cache_min_uses:定义URL经过多少次请求将被缓存
#fastcgi_cache_use_stale:定义哪些情况下可以使用过期缓存
#fastcgi_cache_key:定义fastcgi_cache的key,示例中就以请求的URI作为缓存的key,Nginx会取这个key的md5作为缓存文件,如果设置了缓存哈希目录,Nginx会从后往前取相应的位数做为目录
#fastcgi_cache:定义使用哪个缓存空间
案例3、配置nginx使用fastcgi_cache
[root@www ~]#mkdir /cache/fastcgi
mkdir: 无法创建目录"/cache/fastcgi": 文件已存在
[root@wwwnginx]# vim /usr/share/nginx/html/test.php
<?php
phpinfo()
?>
[root@wwwnginx]# vi nginx.conf
user nginx;
worker_processes 1;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user[$time_local] "$request" $http_host '
'$status $body_bytes_sent"$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
proxy_cache_path /cache/nginx/ levels=1:2keys_zone=mycache:32m;
fastcgi_cache_path /cache/fastcgi/ levels=1:1 keys_zone=fcgicache:10minactive=3m max_size=1g;
upstream upservers {
server 192.168.88.129 max_fails=2fail_timeout=1;
server 192.168.88.130:8080 max_fails=2fail_timeout=1 backup;
}
sendfile on;
#tcp_nopush on;
keepalive_timeout 65;
#gzip on;
include /etc/nginx/conf.d/*.conf;
[root@wwwnginx]#
[[email protected]]# vi default.conf
......
location ~ \.php$ {
# fastcgi_cache off;
#开关fastcgi_cache
fastcgi_cache fcgicache;
#fastcgi_cache:定义使用哪个缓存空间
fastcgi_cache_key $host$request_uri;
#fastcgi_cache_key:定义fastcgi_cache的key,该例中以请求的URI作为缓存的key,Nginx会取这个key的md5作为缓存文件,如果设置了缓存哈希目录,Nginx会从后往前取相应的位数做为目录
fastcgi_cache_min_uses 1;
#fastcgi_cache_min_uses:URL经过多少次请求将被缓存
fastcgi_cache_use_stale error timeout invalid_header http_500;
#fastcgi_cache_use_stale:定义哪些情况下可以使用过期缓存
fastcgi_cache_valid 200 10m;
#fastcgi_cache_valid:定义哪些http头要使用缓存
fastcgi_cache_valid302 3m;
fastcgi_cache_valid any 1m;
root /usr/share/nginx/html;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
include fastcgi_params;
}
访问http://www.field.com:8080/test.php,F12打开控制台
可以看到:
X-Cache:MISS
X-Powered-By:PHP/5.3.3
X-Via:192.168.88.131
此时已在代理服务器生产缓存文件
[root@www 7]#pwd
/cache/fastcgi/e/7
[root@www 7]# ll
总用量 48
-rw-------. 1nginx nginx 46196 4月 20 22:20d41d8cd98f00b204e9800998ecf8427e
[root@www 7]#
连续刷新页面,F12打开控制台
可以看到:
X-Cache:HIT
X-Powered-By:PHP/5.3.3
X-Via:192.168.88.131
案例4、测试fastcgi对系统性能的影响:
使用ab为未添加缓存的Nginx做压力测试
其中参数n为请求的次数,c为一次请求的并发次数,-k为keep_alive,一般出现链接被重置的错误时建议带上-k的参数。
可以使用ab --help 查看ab其他参数
1).关闭fastcgi
[root@wwwnginx]# vim conf.d/default.conf
......
location ~ \.php$ {
fastcgi_cacheoff;
#开关fastcgi_cache
fastcgi_cache fcgicache;
#fastcgi_cache:定义使用哪个缓存空间
fastcgi_cache_key $host$request_uri;
#fastcgi_cache_key:定义fastcgi_cache的key,该例中以请求的URI作为缓存的key,Nginx会取这个key的md5作为缓存文件,如果设置了缓存哈希目录,Nginx会从后往前取相应的位数做为目录
fastcgi_cache_min_uses 1;
#fastcgi_cache_min_uses:URL经过多少次请求将被缓存
fastcgi_cache_use_stale error timeout invalid_header http_500;
#fastcgi_cache_use_stale:定义哪些情况下可以使用过期缓存
fastcgi_cache_valid 200 10m;
#fastcgi_cache_valid:定义哪些http头要使用缓存
fastcgi_cache_valid 302 3m;
fastcgi_cache_valid any 1m;
root /usr/share/nginx/html;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
include fastcgi_params;
}
[[email protected]]# service nginx configtest
nginx: theconfiguration file /etc/nginx/nginx.conf syntax is ok
nginx:configuration file /etc/nginx/nginx.conf test is successful
[[email protected]]# service nginx reload
重新载入 nginx:[确定]
[root@www conf.d]#ab -n 5000 -c 800 -k http://192.168.88.131:8080/test.php
This isApacheBench, Version 2.3 <$Revision: 655654 $>
Copyright 1996Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to TheApache Software Foundation, http://www.apache.org/
Benchmarking192.168.88.131 (be patient)
Completed 500requests
Completed 1000requests
Completed 1500requests
Completed 2000requests
Completed 2500requests
Completed 3000requests
Completed 3500requests
Completed 4000requests
Completed 4500requests
Completed 5000requests
Finished 5000requests
ServerSoftware: nginx/1.8.1
ServerHostname: 192.168.88.131
ServerPort: 8080
DocumentPath: /test.php
DocumentLength: 45383 bytes
ConcurrencyLevel: 800
Time taken for tests: 3.797 seconds
Completerequests: 5000
Failedrequests: 574
(Connect: 0, Receive: 0, Length: 574,Exceptions: 0)
Writeerrors: 0
Non-2xxresponses: 574
Keep-Aliverequests: 0
Totaltransferred: 201815774 bytes
HTMLtransferred: 200975366 bytes
Requests persecond: 1316.95 [#/sec] (mean)
Time perrequest: 607.462 [ms] (mean)
Time perrequest: 0.759 [ms] (mean, acrossall concurrent requests)
Transferrate: 51910.59 [Kbytes/sec]received
Connection Times(ms)
min mean[+/-sd] median max
Connect: 0 175 623.4 0 3003
Processing: 1 193 277.2 75 1688
Waiting: 0 191 276.1 75 1687
Total: 43 368 668.5 75 3029
Percentage ofthe requests served within a certain time (ms)
50% 75
66% 77
75% 527
80% 610
90% 1062
95% 2462
98% 3010
99% 3018
100% 3029 (longest request)
2).打开fastcgi缓存功能
[root@wwwnginx]# vim conf.d/default.conf
location ~ \.php$ {
fastcgi_cache fcgicache;
fastcgi_cache_key$host$request_uri;
fastcgi_cache_min_uses 1;
fastcgi_cache_use_stale error timeout invalid_header http_500;
# fastcgi_cache off;
fastcgi_cache_valid 200 10m;
fastcgi_cache_valid 302 3m;
fastcgi_cache_valid any 1m;
root /usr/share/nginx/html;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
include fastcgi_params;
}
[[email protected]]# service nginx configtest
nginx: theconfiguration file /etc/nginx/nginx.conf syntax is ok
nginx:configuration file /etc/nginx/nginx.conf test is successful
[[email protected]]# service nginx reload
重新载入 nginx:[确定]
[root@www conf.d]# ab -n 5000 -c 800 -khttp://192.168.88.131:8080/test.php
This isApacheBench, Version 2.3 <$Revision: 655654 $>
Copyright 1996Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to TheApache Software Foundation, http://www.apache.org/
Benchmarking192.168.88.131 (be patient)
Completed 500requests
Completed 1000requests
Completed 1500requests
Completed 2000requests
Completed 2500requests
Completed 3000requests
Completed 3500requests
Completed 4000requests
Completed 4500requests
Completed 5000requests
Finished 5000requests
ServerSoftware: nginx/1.8.1
ServerHostname: 192.168.88.131
ServerPort: 8080
DocumentPath: /test.php
DocumentLength: 192 bytes
ConcurrencyLevel: 800
Time taken for tests: 0.887 seconds
Completerequests: 5000
Failedrequests: 4416
(Connect: 0, Receive: 0, Length: 4416,Exceptions: 0)
Writeerrors: 0
Non-2xxresponses: 586
Keep-Alive requests: 0
Totaltransferred: 201907216 bytes
HTMLtransferred: 201002223 bytes
Requests persecond: 5638.79 [#/sec] (mean)
Time perrequest: 141.874 [ms] (mean)
Time perrequest: 0.177 [ms] (mean, acrossall concurrent requests)
Transferrate: 222365.72 [Kbytes/sec]received
Connection Times(ms)
min mean[+/-sd] median max
Connect: 0 5 11.3 0 54
Processing: 9 35 65.5 10 342
Waiting: 7 35 65.4 10 342
Total: 9 40 72.0 10 387
Percentage ofthe requests served within a certain time (ms)
50% 10
66% 11
75% 23
80% 59
90% 104
95% 220
98% 315
99% 351
100% 387 (longest request)
[root@www conf.d]#
3).结果说明:
根据压测结果,800并发,5000请求未添加fastcgi_cache时耗时:
Time taken for tests: 3.797 seconds
添加fastcgi_cache时耗时:
Time taken for tests: 0.887 seconds
效果良好