Ubuntu9.10下 php(FastCGI PHP-FPM)+Nginx+.........
ubuntu安装部分省略N.M.P
下面开始安装编译安装php nginx等所需要包(有的是在ubuntu的源里有的是自己下载源代码编译安装)
一、安装build-essential(包括gcc c++(g++)等)、 autoconf、 automake、 m4
apt-get install build-essential autoconf automake
二、安装支持包
1、安装libjpeg libjpeg-devel
apt-get install libjpeg62 libjpeg62-dev
2、安装libpng libpng-devel
apt-get install libpng12-0 libpng12-dev
3、安装 freetype-devel
apt-get install libfreetype6-dev libfreetype6 freetype2-demos
4、安装libxml2
apt-get install libxml2 libxml2-dev libxml++2.6-2 libxml++2.6-dev
5、安装zlib zlib-devel
apt-get zlib1g zlib1g-dev zlib1g-dbg
6、安装glib2 glib2-devel
apt-get install libglib2.0-0 libglib2.0-dev
7、安装bzip2 bzip2-devel
apt-get bzip2 libbz2-dev
8、安装ncurses ncurses-devel
apt-get install libncurses5 libncurses5-dev
9、安装curl curl-devel
apt-get install curl libcurl3 libcurl4-dev libcurl4-openssl-dev
10、安装e2fsprogs e2fsprogs-devel
apt-get install e2fsprogs uuid-dev
11、安装krb5 krb5-devel
apt-get install libkrb5-3 libkrb5-dev
12、安装libidn libidn-devel
apt-get install libidn11 libidn11-dev
13、安装openssl openssl-devel
apt-get install openssl libssl-dev
14、装openldap openldap-devel
apt-get libldap-2.4-2 libldap2-dev
15、libmcrypt libmcrypt-dev
apt-get install libmcrypt4 libmcrypt-dev
16、libltdl libltdl-dev
apt-get install libltdl7 libltdl-dev
17、libmhash libmhash-dev
apt-get install libmhash2 libmhash-dev
18、mcrypt
apt-get install mcrypt
19、gd2
apt-get install libgd2-xpm
20、安装mysql
apt-get install mysql-server
21、安装sqlite libsqlite-dev
apt-get install sqlite libsqlite-dev
22、安装mysql-dev
apt-get libmysqlclient libmysqlclient-dev libmysqlclient16 libmysqlclient16-dev
23、libsasl2-dev
apt-get install libsasl2-dev
24、libticonv3 libticonv-dev
24、安装libiconv-1.13.1
下载libiconv-1.13.1.tar.tar
tar zxvf libiconv-1.13.1.tar.tar
cd llibiconv-1.13.1
./configure --prefix=/usr/local
make
make install
25php的安装
下载php源代码我用的是php5.3.1
下载fpm-php源代码
解压缩
生成fpm的patch文件
./generate-fpm-patch
给php打fpm补丁
进入php源码目录
patch -p1 < ../fpm.patch
打完补丁后运行
./buildconf --force
完了
./configure --prefix=/usr/local/webserver/php --with-mysql --with-mysqli --with-mysql-sock --with-iconv-dir=/usr/local --with-
iconv-dir=/usr/local --with-freetype-dir --with-jpeg-dir --with-png-dir --with-zlib --with-libxml-dir --enable-xml --disable-rpath --
enable-bcmath --enable-shmop --enable-sysvsem --enable-inline-optimization --with-curl --with-curlwrappers --enable-mbregex
--with-fpm --with-libevent --enable-mbstring --with-mcrypt --with-gd --enable-gd-native-ttf --with-openssl --with-mhash --
enable-pcntl --enable-sockets --with-ldap --with-ldap-sasl --with-xmlrpc --enable-zip --enable-soap --with-pear
完了
make ZEND_EXTRA_LIBS='-liconv'
完了
make test
完了
make install
meke make test 时间都很长
完成后
cp php.ini-production /usr/local/webserver/php/lib/php.ini
cd ../
curl http://pear.php.net/go-pear | /usr/local/webserver/php/bin/php
一路回车吧
接下来安装php的扩展模块
tar zxvf memcache-2.2.5.tgz
cd memcache-2.2.5/
/usr/local/webserver/php/bin/phpize
./configure --with-php-config=/usr/local/webserver/php/bin/php-config
make
make install
cd ../
tar jxvf eaccelerator-0.9.6-rc1.tar.bz2
cd eaccelerator-0.9.6-rc1
/usr/local/webserver/php/bin/phpize
./configure --enable-eaccelerator=shared --with-php-config=/usr/local/webserver/php/bin/php-config
make
make install
cd ../
tar zxvf PDO_MYSQL-1.0.2.tgz
cd PDO_MYSQL-1.0.2/
/usr/local/webserver/php/bin/phpize
./configure --with-php-config=/usr/local/webserver/php/bin/php-config --with-pdo-mysql=/usr/local/webserver/mysql
make
make install
cd ../
apt-get install imagemagick
(特别注意要安装dev的,不然下面的那个不能编译的)
tar zxvf imagick-2.3.0.tgz
cd imagick-2.3.0/
/usr/local/webserver/php/bin/phpize
./configure --with-php-config=/usr/local/webserver/php/bin/php-config
make
make install
cd ../
修改php.ini文件
手工修改:查找/usr/local/webserver/php/lib/php.ini中的extension_dir = "./"
修改为extension_dir = "/usr/local/webserver/php/lib/php/extensions/no-debug-non-zts-20090613/"
并在此行后增加以下几行,然后保存:
extension = "memcache.so"
extension = "pdo_mysql.so"
extension = "imagick.so"
设置下时区date.tiemzone="PRC"
配置eAccelerator加速PHP(据说比zend好用)
mkdir -p /usr/local/webserver/eaccelerator_cache
vi /usr/local/webserver/php/lib/php.ini
按shift+g键跳到配置文件的最末尾,加上以下配置信息
[eaccelerator]
zend_extension="/usr/local/webserver/php/lib/php/extensions/no-debug-non-zts-20090613/eaccelerator.so"
eaccelerator.shm_size="64"
eaccelerator.cache_dir="/usr/local/webserver/eaccelerator_cache"
eaccelerator.enable="1"
eaccelerator.optimizer="1"
eaccelerator.check_mtime="1"
eaccelerator.debug="0"
eaccelerator.filter=""
eaccelerator.shm_max="0"
eaccelerator.shm_ttl="3600"
eaccelerator.shm_prune_period="3600"
eaccelerator.shm_only="0"
eaccelerator.compress="1"
eaccelerator.compress_level="9"
创建www用户和组,以及供虚拟主机使用的目录
groupadd www
useradd -g www www
mkdir -p /usr/local/www/www
chmod +w /usr/local/www/www
chown -R www:www /usr/local/www/www
配置php-fpm的配置文件(位置在/etc/php-fpm.conf)
一下是我的配置文件,注意的地只有几个pid文件的位置 这个文件在php-fpm的控制脚本里面要用,不然没办法停止php-fpm
还有连接日志、错误日志的位置要建立好相应的目录 并且给相应权限 chmod +w chown -R www:www
还有就是几个数字 都是英文的而且有解释自己根据自己的情况来吧!这个需要按照实际情况调整的,服务器配置不可能一下子就ok的,要综合各种情况和
环境来设置这些性能参数
<?xml version="1.0" ?>
<configuration>
All relative paths in this config are relative to php's install prefix
<section name="global_options">
Pid file
<value name="pid_file">/var/run/php-fpm.pid</value>
Error log file
<value name="error_log">/usr/local/webserver/php/logs/php-fpm.log</value>
Log level
<value name="log_level">notice</value>
When this amount of php processes exited with SIGSEGV or SIGBUS ...
<value name="emergency_restart_threshold">10</value>
... in a less than this interval of time, a graceful restart will be initiated.
Useful to work around accidental curruptions in accelerator's shared memory.
<value name="emergency_restart_interval">1m</value>
Time limit on waiting child's reaction on signals from master
<value name="process_control_timeout">5s</value>
Set to 'no' to debug fpm
<value name="daemonize">yes</value>
</section>
<workers>
<section name="pool">
Name of pool. Used in logs and stats.
<value name="name">default</value>
Address to accept fastcgi requests on.
Valid syntax is 'ip.ad.re.ss:port' or just 'port' or '/path/to/unix/socket'
<value name="listen_address">127.0.0.1:9000</value>
<value name="listen_options">
Set listen(2) backlog
<value name="backlog">-1</value>
Set permissions for unix socket, if one used.
In Linux read/write permissions must be set in order to allow connections from web server.
Many BSD-derrived systems allow connections regardless of permissions.
<value name="owner"></value>
<value name="group"></value>
<value name="mode">0666</value>
</value>
Additional php.ini defines, specific to this pool of workers.
<value name="php_defines">
<value name="sendmail_path">/usr/sbin/sendmail -t -i</value>
<value name="display_errors">1</value>
</value>
Unix user of processes
<value name="user">www</value>
Unix group of processes
<value name="group">www</value>
Process manager settings
<value name="pm">
Sets style of controling worker process count.
Valid values are 'static' and 'apache-like'
<value name="style">static</value>
Sets the limit on the number of simultaneous requests that will be served.
Equivalent to Apache MaxClients directive.
Equivalent to PHP_FCGI_CHILDREN environment in original php.fcgi
Used with any pm_style.
<value name="max_children">128</value>
Settings group for 'apache-like' pm style
<value name="apache_like">
Sets the number of server processes created on startup.
Used only when 'apache-like' pm_style is selected
<value name="StartServers">20</value>
Sets the desired minimum number of idle server processes.
Used only when 'apache-like' pm_style is selected
<value name="MinSpareServers">5</value>
Sets the desired maximum number of idle server processes.
Used only when 'apache-like' pm_style is selected
<value name="MaxSpareServers">35</value>
</value>
</value>
The timeout (in seconds) for serving a single request after which the worker process will be terminated
Should be used when 'max_execution_time' ini option does not stop script execution for some reason
'0s' means 'off'
<value name="request_terminate_timeout">0s</value>
The timeout (in seconds) for serving of single request after which a php backtrace will be dumped to slow.log file
'0s' means 'off'
<value name="request_slowlog_timeout">0s</value>
The log file for slow requests
<value name="slowlog">logs/slow.log</value>
Set open file desc rlimit
<value name="rlimit_files">65535</value>
Set max core size rlimit
<value name="rlimit_core">0</value>
Chroot to this directory at the start, absolute path
<value name="chroot"></value>
Chdir to this directory at the start, absolute path
<value name="chdir"></value>
Redirect workers' stdout and stderr into main error log.
If not set, they will be redirected to /dev/null, according to FastCGI specs
<value name="catch_workers_output">yes</value>
How much requests each process should execute before respawn.
Useful to work around memory leaks in 3rd party libraries.
For endless request processing please specify 0
Equivalent to PHP_FCGI_MAX_REQUESTS
<value name="max_requests">102400</value>
Comma separated list of ipv4 addresses of FastCGI clients that allowed to connect.
Equivalent to FCGI_WEB_SERVER_ADDRS environment in original php.fcgi (5.2.2+)
Makes sense only with AF_INET listening socket.
<value name="allowed_clients">127.0.0.1</value>
Pass environment variables like LD_LIBRARY_PATH
All $VARIABLEs are taken from current environment
<value name="environment">
<value name="HOSTNAME">$HOSTNAME</value>
<value name="PATH">/usr/local/bin:/usr/bin:/bin</value>
<value name="TMP">/tmp</value>
<value name="TMPDIR">/tmp</value>
<value name="TEMP">/tmp</value>
<value name="OSTYPE">$OSTYPE</value>
<value name="MACHTYPE">$MACHTYPE</value>
<value name="MALLOC_CHECK_">2</value>
</value>
</section>
</workers>
</configuration>
启动下php-fpm看
ulimit -SHn 65535
service php-fpm start (安装的时候自己会生成一个启动脚本在inti.d下)
ulimit -SHn 65535必须和配置文件里相对应否则会产生错误,可以看日志文件就明白了。
如果没有错误提示恭喜,完成了,如果有错误按照提示解决
主要的一起错误就shmmax的值,在下面优化内核参数里面有的。
你还可以用netstat -nltp | grep php-fpm 确认下,监听的端口是9000
php到此结束
接下来是nginx
下载nginx
我用的是0.8.28
安装前要先安装Nginx所需的pcre库
tar zxvf pcre-8.00.tar.gz
cd pcre-8.00/
./configure --enable-utf8
make
make install
注意看下产生的lib的位置,如果nginx启动出错要ln -s 到相应目录
ln -s /usr/local/lib/libpcre.so.0 /usr/lib/libpcre.so.0
tar zxvf nginx-0.8.28.tar.gz
cd nginx-0.8.28/
./configure --user=www --group=www --prefix=/usr/local/webserver/nginx --http-client-body-temp-
path=/var/cache/nginx/client_body_temp --with-select_module --with-poll_module --with-http_sub_module --with-
http_stub_status_module --with-http_gzip_static_module --with-http_dav_module --with-http_flv_module --with-
http_secure_link_module
make
make install
安装完成后
修改nginx的配置文件,不得不说的是nginx的配置文件看着真是舒服(/usr/local/webserver/nginx/conf/nginx.conf)
我的配置文件如下 (一个网站 www.cfsyzx.cn 一个用来查看nginx的状态 status.cfsyzx.cn)
需要注意的是worker_cpu_affinity和你的cpu又关系的,另外连接日志,错误日志,pid文件路径要注意下。
user www www;
worker_processes 8;
worker_cpu_affinity 0001 0100 1000 0010 0001 0100 1000 0010;
error_log /var/log/nginx/nginx_error.log crit;
pid /usr/local/webserver/nginx/nginx.pid;
#Specifies the value for maximum file descriptors that can be opened by this process.
worker_rlimit_nofile 65535;
events
{
use epoll;
worker_connections 65535;
}
http
{
include mime.types;
default_type application/octet-stream;
#charset gb2312;
server_names_hash_bucket_size 128;
client_header_buffer_size 32k;
large_client_header_buffers 4 32k;
client_max_body_size 8m;
sendfile on;
tcp_nopush on;
keepalive_timeout 60;
tcp_nodelay on;
fastcgi_connect_timeout 300;
fastcgi_send_timeout 300;
fastcgi_read_timeout 300;
fastcgi_buffer_size 64k;
fastcgi_buffers 4 64k;
fastcgi_busy_buffers_size 128k;
fastcgi_temp_file_write_size 128k;
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/css application/xml;
gzip_vary on;
#limit_zone crawler $binary_remote_addr 10m;
server
{
listen 80;
server_name www.cfsyzx.cn;
index index.html index.htm index.php;
root /usr/local/www/www;
#limit_conn crawler 20;
location ~ .*\.(php|php5)?$
{
#fastcgi_pass unix:/tmp/php-cgi.sock;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
include fcgi.conf;
}
location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$
{
expires 30d;
}
location ~ .*\.(js|css)?$
{
expires 1h;
}
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 /var/log/nginx/access.log access;
}
server
{
listen 80;
server_name status.cfsyzx.cn;
location / {
stub_status on;
access_log off;
}
}
}
根据配置文件的内容建立相应目录用来存放日志,注意设置权限 chmod +w chown -R www:www
在/usr/local/webserver/nginx/conf/目录中创建fcgi.conf文件内容如下:
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;
完成
ulimit -SHn 65535
service php-fpm start
/usr/local/webserver/nginx/sbin/nginx
在/usr/local/www/www 建立一个php文件
<?php
phpinfo();
?>;
好了完成了 看看你的php信息呵呵,漂亮吧,基本上全部都支持了!!!
下来时优化linux内核参数
vi /etc/sysctl.conf
在末尾增加以下内容:
# Add
net.ipv4.tcp_max_syn_backlog = 65536
net.core.netdev_max_backlog = 32768
net.core.somaxconn = 32768
net.core.wmem_default = 8388608
net.core.rmem_default = 8388608
net.core.rmem_max = 16777216
net.core.wmem_max = 16777216
net.ipv4.tcp_timestamps = 0
net.ipv4.tcp_synack_retries = 2
net.ipv4.tcp_syn_retries = 2
net.ipv4.tcp_tw_recycle = 1
#net.ipv4.tcp_tw_len = 1
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_mem = 94500000 915000000 927000000
net.ipv4.tcp_max_orphans = 3276800
#net.ipv4.tcp_fin_timeout = 30
#net.ipv4.tcp_keepalive_time = 120
net.ipv4.ip_local_port_range = 1024 65535
kernel.shmmax= 内存大小/2*1024*1024
使配置立即生效:
/sbin/sysctl -p
下来就是教php和nginx自动启动
需要安装一个软件包
apt-get install sysv-rc-conf
编辑/etc/init.d/下的php-fpm
注意几个文件路径,另外这个启动脚本有个bug ,在启动那里加上判断下 php-fpm是否已经启动如果已经启动,给出提示!
在 /etc/init.d/下建立nginx
vi nginx
内容如下:
#! /bin/sh
### BEGIN INIT INFO
# Provides: php-fpm
# Required-Start: $all
# Required-Stop: $all
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: starts Nginx
# Description: starts the Nginx Process Manager daemon
### END INIT INFO
nginx_BIN=/usr/local/webserver/nginx/sbin/nginx
nginx_CONF=/usr/local/webserver/nginx/conf/nginx.conf
nginx_PID=/usr/local/webserver/nginx/nginx.pid
nginx_opts="-c $nginx_CONF"
wait_for_pid () {
try=0
while test $try -lt 35 ; do
case "$1" in
'created')
if [ -f "$2" ] ; then
try=''
break
fi
;;
'removed')
if [ ! -f "$2" ] ; then
try=''
break
fi
;;
esac
echo -n .
try=`expr $try + 1`
sleep 1
done
}
case "$1" in
start)
if [ -r $nginx_PID ];then
echo "nginx has been running... "
exit 1
fi
echo -n "Starting nginx "
ulimit -SHn 65535
$nginx_BIN $nginx_opts
if [ "$?" != 0 ] ; then
echo " failed"
exit 1
fi
wait_for_pid created $nginx_PID
if [ -n "$try" ] ; then
echo " failed"
exit 1
else
echo " done"
fi
;;
stop)
echo -n "Gracefully shutting down nginx "
if [ ! -r $nginx_PID ] ; then
echo "warning, no pid file found - nginx is not running ?"
exit 1
fi
kill -QUIT `cat $nginx_PID`
wait_for_pid removed $nginx_PID
if [ -n "$try" ] ; then
echo " failed.Try force-quit"
exit 1
else
echo " done"
fi
;;
force-quit)
echo -n "Terminating nginx "
if [ ! -r $nginx_PID ] ; then
echo "warning, no pid file found - nginx is not running ?"
exit 1
fi
kill -TERM `cat $nginx_PID`
wait_for_pid removed $nginx_PID
if [ -n "$try" ] ; then
echo " failed"
exit 1
else
echo " done"
fi
;;
restart)
$0 stop
$0 start
;;
reload)
echo -n "Reload service nginx "
if [ ! -r $nginx_PID ] ; then
echo "warning, no pid file found - nginx is not running ?"
exit 1
fi
kill -USR2 `cat $nginx_PID`
echo " done"
;;
*)
echo "Usage: $0 {start|stop|force-quit|restart|reload}"
exit 1
;;
esac
保存
运行 sysv-rc-conf
把php-fpm和nginx 的2 3 4 5 打钩q键退出!
完成!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
接下来是些零散的资料
ps -ef | grep apache | grep -v grep | wc -l
第一项:查看所有进程信息
第二项:过滤获取apache进程
第三项:反选去除本身grep干扰项
第四项:统计行数
==============================================
Nginx保护目录的配置如下,目录密码保护文件是 dynamic/htpasswd
if (!-e $request_filename) {
rewrite ^(.*)$ /hbcms404.php last;
}
location ~ /(admin/.*|phpMyAdmin*|include/.*|setup/.*) {
location ~ \.php$ {
fastcgi_pass 127.0.0.1:9000;
}
auth_basic "Restricted";
auth_basic_user_file dynamic/htpasswd;
}
location ~ \.php$ {
fastcgi_pass 127.0.0.1:9000;
}
目录密码保护的配置,如果不加红色部分代码,php文件不会执行,会出现php文件下载的提示。
保护目录的配置,如果放在绿色代码后面,虽然会提示要输入密码,但是,不输入目录保护密码也会执行php并显示出来。
多次测试得到上面的结果,有些糊涂,记录一下,以便备查。
生成密码文件:
htpasswd -b -c htpasswd username password;
===================================================
Nginx身份验证
nginxstatus做身份验证:
#cd /usr/local/nginx/conf
#mkdir htpasswd
/usr/local/apache2/bin/htpasswd -c /usr/local/nginx/conf/htpasswd/zhang zhang #添加用户名为zhang
#或者
htpasswd -c /usr/local/nginx/conf/htpasswd/zhang zhang #添加用户名为zhang
New password: (此处输入你的密码)
Re-type new password: (再次输入你的密码)
Adding password for user
配置nginx
location ~ ^/(zhang)/ {
root /htdocs/count;
auth_basic "LT-COUNT-TongJi";
auth_basic_user_file /usr/local/nginx/conf/htpasswd/zhang;
}
看看打开页面是否需要输入用户名和密码!
======================================================
worker_processes指明了nginx要开启的进程数,据官方说法,一般开一个就够了,多开几个,可以减少机器io带来的影响。
据实践表明,nginx的这个参数在一般情况下开4个或8个就可以了,再往上开的话优化不太大。据另一种说法是,nginx开启太多的进程,会影响主进程
调度,所以占用的cpu会增高,这个说法我个人没有证实,估计他们是开了一两百个进程来对比的吧。
worker_processes配置的一些注意事项:
1、worker_cpu_affinity配置最好是能写上
我这里服务器多数是双核超线程,相当于4cpu,我一般开8进程,所以这个配置就是这样:
worker_cpu_affinity 0001 0100 1000 0010 0001 0100 1000 0010;
另,worker_cpu_affinity不是什么时候都能用的,我没有认真研究并罗列所有情况,只知道2.4内核的机器用不了,如果用不了的话,那么最好是加大
worker_processes进程数,这样分配cpu就会平均一点啦,如果不平均只好多重启几下。
2、worker_rlimit_nofile配置要和系统的单进程打开文件数一致,千万不要再画蛇添足地除以worker_processes。
我现在在linux 2.6内核下开启文件打开数为65535,worker_rlimit_nofile就相应应该填写65535。
这是因为nginx调度时分配请求到进程并不是那么的均衡,所以假如填写10240,总并发量达到3-4万时就有进程可能超过10240了,这时会返回502错
误。
========================================================
over