CentOS 5.6下编译安装LNMP平台(Nginx1.0+PHP5.3.6+Mysql5.5.11)

发表时间:2011-09-15 文章分类:linux 阅读:155396

文章链接:http://www.webzone8.com/article/333.html
  一、获取相关开源程序
  1、本文基本以源码编译为主,首先需要安装基础编译环境所需要的软件和库。本文安装CentOS系统时只安装最基础的包(安装时软件套件选择时只选了Server一项),下面的所需要的包可根据自己系统环境情况自行调整。
  a)、通过CentOS光盘安装(以光盘作为Yum源)

mkdir /media/CentOS/
mount /dev/cdrom /media/CentOS/

yum -y --disablerepo=\* --enablerepo=c5-media install gcc gcc-c++ autoconf \
libjpeg libjpeg-devel libpng libpng-devel freetype freetype-devel libxml2 \
libxml2-devel zlib zlib-devel glibc glibc-devel glib2 glib2-devel bzip2 \
bzip2-devel  ncurses ncurses-devel curl curl-devel e2fsprogs e2fsprogs-devel \
krb5 krb5-devel libidn libidn-devel openssl openssl-devel libtool  libtool-libs \
libevent-devel libevent openldap openldap-devel nss_ldap openldap-clients \
openldap-servers libtool-ltdl libtool-ltdl-devel bison
 

     b)、通过mirrors.163.com安装(以mirrors.163.com为Yum源)

mv /etc/yum.repos.d/CentOS-Base.repo /etc/yum.repos.d/CentOS-Base.repo.backup
wget http://mirrors.163.com/.help/CentOS5-Base-163.repo
yum makecache
 
yum -y --enablerepo=c5-media install gcc gcc-c++ autoconf \
libjpeg libjpeg-devel libpng libpng-devel freetype freetype-devel libxml2 \
libxml2-devel zlib zlib-devel glibc glibc-devel glib2 glib2-devel bzip2 \
bzip2-devel  ncurses ncurses-devel curl curl-devel e2fsprogs e2fsprogs-devel \
krb5 krb5-devel libidn libidn-devel openssl openssl-devel libtool  libtool-libs \
libevent-devel libevent openldap openldap-devel nss_ldap openldap-clients \
openldap-servers libtool-ltdl libtool-ltdl-devel bison
 

  2、下载最新的Nginx、Mysql、PHP程序及相关库的源码包
mkdir -p /data/software
cd /data/software
wget http://nginx.org/download/nginx-1.0.0.tar.gz
wget http://cn.php.net/get/php-5.3.6.tar.gz/from/this/mirror
wget http://dev.mysql.com/get/Downloads/MySQL-5.5/mysql-5.5.11.tar.gz/from/http://mysql.ntu.edu.tw/
wget http://ftp.gnu.org/pub/gnu/libiconv/libiconv-1.13.1.tar.gz
wget http://downloads.sourceforge.net/mcrypt/libmcrypt-2.5.8.tar.gz?modtime=1171868460&big_mirror=0"
wget http://downloads.sourceforge.net/mcrypt/mcrypt-2.6.8.tar.gz?modtime=1194463373&big_mirror=0"

wget http://pecl.php.net/get/memcache-2.2.6.tgz
wget http://downloads.sourceforge.net/mhash/mhash-0.9.9.9.tar.gz?modtime=1175740843&big_mirror=0"
wget ftp://ftp.csx.cam.ac.uk/pub/software/programming/pcre/pcre-8.12.tar.gz
wget http://bart.eaccelerator.net/source/0.9.6.1/eaccelerator-0.9.6.1.tar.bz2
wget http://pecl.php.net/get/PDO_MYSQL-1.0.2.tgz
wget ftp://mirror.aarnet.edu.au/pub/imagemagick/ImageMagick-6.6.9-9.tar.gz
wget http://pecl.php.net/get/imagick-3.0.0.tgz
wget http://www.cmake.org/files/v2.8/cmake-2.8.4.tar.gz

二、安装MySQL 5.5.11
  1、首先安装CMAKE(Mysql5.5.11已经采用CMAKE编译)
tar zxvf cmake-2.8.4.tar.gz
cd cmake-2.8.4
./configure --prefix=/usr
make
make install
cd ..

    2、安装MySQL 5.5.11
  a)新建一个用于运行MySQL的用户
/usr/sbin/groupadd mysql
/usr/sbin/useradd -g mysql mysql

     b)解包并编译安装MySQL
tar xvf mysql-5.5.11.tar.gz
cd mysql-5.5.11
 
cmake . -DCMAKE_INSTALL_PREFIX=/usr/local/mysql/ \
-DMYSQL_DATADIR=/data/www/mysql/data \
-DMYSQL_UNIX_ADDR=/data/www/mysql/mysqld.sock \
-DWITH_INNOBASE_STORAGE_ENGINE=1 \
-DWITH_MYISAM_STORAGE_ENGINE=1 \
-DENABLED_LOCAL_INFILE=1 \
-DMYSQL_TCP_PORT=3306 \
-DWITH_EXTRA_CHARSETS:STRING=utf8,gbk \
-DDEFAULT_CHARSET=utf8 \
-DDEFAULT_COLLATION=utf8_general_ci \
-DMYSQL_UNIX_ADDR=/data/www/mysql/mysql.sock \
-DWITH_DEBUG=0 \
-DWITH_READLINE=1 \
-DWITH_SSL=yes \
-DSYSCONFDIR=/data/www/mysql
 
make
make install
cd ..

    c)将MySQL安装目录的权限赋予mysql用户
chmod +w /usr/local/mysql
chown -R mysql:mysql /usr/local/mysql

    d)创建MySQL数据库存放目录
mkdir -p /data/www/mysql/data/
mkdir -p /data/www/mysql/binlog/
mkdir -p /data/www/mysql/relaylog/
chown -R mysql:mysql /data/www/mysql/

    e)以mysql用户帐号的身份建立数据表
/usr/local/mysql/scripts/mysql_install_db --basedir=/usr/local/mysql --datadir=/data/www/mysql/data --user=mysql

    f)创建my.cnf配置文件
/data/www/mysql/my.cnf
 
[client]
default-character-set=utf8
port    = 3306
socket  = /tmp/mysql.sock
 
[mysqld]
character-set-server = utf8
replicate-ignore-db = mysql
replicate-ignore-db = test
replicate-ignore-db = information_schema
user    = mysql
port    = 3306
socket  = /tmp/mysql.sock
basedir = /usr/local/mysql
datadir = /data/www/mysql/data
log-error = /data/www/mysql/mysql_error.log
pid-file = /data/www/mysql/mysql.pid
open_files_limit    = 10240
back_log = 600
max_connections = 5000
max_connect_errors = 6000
table_cache = 614
external-locking = FALSE
max_allowed_packet = 32M
sort_buffer_size = 1M
join_buffer_size = 1M
thread_cache_size = 300
#thread_concurrency = 8
query_cache_size = 512M
query_cache_limit = 2M
query_cache_min_res_unit = 2k
default-storage-engine = MyISAM
thread_stack = 192K
transaction_isolation = READ-COMMITTED
tmp_table_size = 246M
max_heap_table_size = 246M
long_query_time = 3
log-slave-updates
log-bin = /data/www/mysql/binlog/binlog
binlog_cache_size = 4M
binlog_format = MIXED
max_binlog_cache_size = 8M
max_binlog_size = 1G
relay-log-index = /data/www/mysql/relaylog/relaylog
relay-log-info-file = /data/www/mysql/relaylog/relaylog
relay-log = /data/www/mysql/relaylog/relaylog
expire_logs_days = 30
key_buffer_size = 256M
read_buffer_size = 1M
read_rnd_buffer_size = 16M
bulk_insert_buffer_size = 64M
myisam_sort_buffer_size = 128M
myisam_max_sort_file_size = 10G
myisam_repair_threads = 1
myisam_recover
 
interactive_timeout = 120
wait_timeout = 120
 
skip-name-resolve
slave-skip-errors = 1032,1062,126,1114,1146,1048,1396
 
server-id = 1
 
innodb_additional_mem_pool_size = 16M
innodb_buffer_pool_size = 512M
innodb_data_file_path = ibdata1:256M:autoextend
innodb_file_io_threads = 4
innodb_thread_concurrency = 8
innodb_flush_log_at_trx_commit = 2
innodb_log_buffer_size = 16M
innodb_log_file_size = 128M
innodb_log_files_in_group = 3
innodb_max_dirty_pages_pct = 90
innodb_lock_wait_timeout = 120
innodb_file_per_table = 0
 
log-slow-queries = /data/www/mysql/slow.log
long_query_time = 10
log-queries-not-using-indexes
 
[mysqldump]
quick
max_allowed_packet = 32M

    g)创建管理MySQL数据库的shell脚本
vi /data/www/mysql/mysql
 
#!/bin/bash
 
mysql_username="admin"
mysql_password="000000"
 
function_start_mysql()
{
    printf "Starting MySQL...\n"
    /bin/sh /usr/local/mysql/bin/mysqld_safe --defaults-file=/data/www/mysql/my.cnf 2>&1 > /dev/null &
}
 
function_stop_mysql()
{
    printf "Stoping MySQL...\n"
    /usr/local/mysql/bin/mysqladmin -u ${mysql_username} -p${mysql_password} -S /tmp/mysql.sock shutdown
}
 
function_restart_mysql()
{
    printf "Restarting MySQL...\n"
    function_stop_mysql
    sleep 5
    function_start_mysql
}
 
function_kill_mysql()
{
    kill -9 $(ps -ef | grep 'bin/mysqld_safe' | grep ${mysql_port} | awk '{printf $2}')  
    kill -9 $(ps -ef | grep 'libexec/mysqld' | grep ${mysql_port} | awk '{printf $2}')  
}
 
if [ "$1" = "start" ]; then
    function_start_mysql
elif [ "$1" = "stop" ]; then
    function_stop_mysql
elif [ "$1" = "restart" ]; then
function_restart_mysql
elif [ "$1" = "kill" ]; then
function_kill_mysql
else
    printf "Usage: /data/www/mysql/mysql {start|stop|restart|kill}\n"
fi

    赋予shell脚本可执行权限
chmod +x /data/www/mysql/mysql

 h)测试Mysql的启动的关闭
  启动MySQL
/data/www/mysql/mysql start

     通过命令行登录管理MySQL服务器(提示输入密码时直接回车,缺省的Mysql的root用户无密码)
/usr/local/mysql/bin/mysql -u root -p -S /tmp/mysql.sock

     创建一个具有root权限的用户:admin,密码是:000000(用于上面建的管理脚本中的mysqladmin)
GRANT ALL PRIVILEGES ON *.* TO 'admin'@'localhost' IDENTIFIED BY '000000';
GRANT ALL PRIVILEGES ON *.* TO 'admin'@'127.0.0.1' IDENTIFIED BY '000000';

    停止MySQL:
/data/www/mysql/mysql stop

  g)、设置libmysqlclient的软链,防止编译其它依赖Mysql软件时出现libmysqlclient.so.18: cannot open shared object file 的错误
  32位系统下的MYSQL客户端软链接
ln -s /usr/local/mysql/lib/libmysqlclient.so.18 /usr/lib/libmysqlclient.so.18

      64位系统下的MYSQL客户端软链接
ln -s /usr/local/mysql/lib/libmysqlclient.so.18 /usr/lib64/libmysqlclient.so.18

三、安装PHP 5.3.6(FastCGI模式)
  1、编译安装PHP 5.3.6所需的支持库
  libiconv(加强系统对支持字符编码转换的功能)
tar zxvf libiconv-1.13.1.tar.gz
cd libiconv-1.13.1/
./configure --prefix=/usr/local
make
make install
cd ..

     libmcrypt(加密算法库,PHP扩展mcrypt功能对此库有依耐关系,要使用mcrypt必须先安装此库)
tar zxvf libmcrypt-2.5.8.tar.gz
cd libmcrypt-2.5.8
./configure
make
make install
/sbin/ldconfig
 
cd libltdl/
./configure --enable-ltdl-install
make
make install
cd ../../

    编译安装libltdl时可能会遇到的错误:
/bin/sh ./libtool --mode=compile gcc -DHAVE_CONFIG_H -I. -I. -I.     -g -O2 -c ltdl.c
mkdir .libs
 gcc -DHAVE_CONFIG_H -I. -I. -I. -g -O2 -c ltdl.c  -fPIC -o .libs/ltdl.o
 gcc -DHAVE_CONFIG_H -I. -I. -I. -g -O2 -c ltdl.c -o ltdl.o >/dev/null 2>&1
/bin/sh ./libtool --mode=link gcc  -g -O2  -o libltdl.la -rpath /usr/local/lib -no-undefined -version-info 4:0:1 ltdl.lo -ldl
./libtool: line 3965: ELF [0-9][0-9]*-bit [LM]SB (shared object|dynamic lib ): command not found
./libtool: line 3965: ELF [0-9][0-9]*-bit [LM]SB (shared object|dynamic lib ): command not found
./libtool: line 3965: ELF [0-9][0-9]*-bit [LM]SB (shared object|dynamic lib ): command not found
./libtool: line 3965: ELF [0-9][0-9]*-bit [LM]SB (shared object|dynamic lib ): command not found

产生原因:源码包中LIBTOOL版本过低。
  解决方法:让编译时调用系统的LIBTOOL。修改Makefile文件,LIBTOOL=$(SHELL)$(top_builddir)/libtool 为LIBTOOL=$(SHELL) /usr/bin/libtool
  参考文档:http://bbs.linuxtone.org/thread-2362-1-1.html

建立libmcrypt相关库的软连接,为编译mcrypt作准备。因为mcrypt依赖libmcrypt。
  #如果是CENTOS 5.6(64位)
ln -sf /usr/local/lib/libmcrypt.la /usr/lib64/libmcrypt.la
ln -sf /usr/local/lib/libmcrypt.so /usr/lib64/libmcrypt.so
ln -sf /usr/local/lib/libmcrypt.so.4 /usr/lib64/libmcrypt.so.4
ln -sf /usr/local/lib/libmcrypt.so.4.4.8 /usr/lib64/libmcrypt.so.4.4.8
ln -sf /usr/local/bin/libmcrypt-config /usr/bin/libmcrypt-config
ln -sf /usr/local/lib/libiconv.so.2 /usr/lib64/libiconv.so.2
ldconfig

     #如果是CENTOS 5.6(32位)
ln -sf /usr/local/lib/libmcrypt.la /usr/lib/libmcrypt.la
ln -sf /usr/local/lib/libmcrypt.so /usr/lib/libmcrypt.so
ln -sf /usr/local/lib/libmcrypt.so.4 /usr/lib/libmcrypt.so.4
ln -sf /usr/local/lib/libmcrypt.so.4.4.8 /usr/lib/libmcrypt.so.4.4.8
ln -sf /usr/local/bin/libmcrypt-config /usr/bin/libmcrypt-config
ln -sf /usr/local/lib/libiconv.so.2 /usr/lib/libiconv.so.2
ldconfig

mhash(hash加密算法库)
tar zxvf mhash-0.9.9.9.tar.gz
cd mhash-0.9.9.9
./configure
make
make install
cd ..

建立libmhash相关库的软连接,为编译mcrypt作准备。mcrypt也依赖libmhash。
  #如果是CENTOS 5.6(64位)

ln -sf /usr/local/lib/libmhash.a /usr/lib64/libmhash.a
ln -sf /usr/local/lib/libmhash.la /usr/lib64/libmhash.la
ln -sf /usr/local/lib/libmhash.so /usr/lib64/libmhash.so
ln -sf /usr/local/lib/libmhash.so.2 /usr/lib64/libmhash.so.2
ln -sf /usr/local/lib/libmhash.so.2.0.1 /usr/lib64/libmhash.so.2.0.1
ldconfig
 

     #如果是CENTOS 5.6(32位)

ln -sf /usr/local/lib/libmhash.a /usr/lib/libmhash.a
ln -sf /usr/local/lib/libmhash.la /usr/lib/libmhash.la
ln -sf /usr/local/lib/libmhash.so /usr/lib/libmhash.so
ln -sf /usr/local/lib/libmhash.so.2 /usr/lib/libmhash.so.2
ln -sf /usr/local/lib/libmhash.so.2.0.1 /usr/lib/libmhash.so.2.0.1
ldconfig
 


tar zxvf mcrypt-2.6.8.tar.gz
cd mcrypt-2.6.8/
/sbin/ldconfig
./configure
make
make install
cd ..
 

./configure时可能会报这个错:/bin/rm: cannot remove `libtoolT’: No such file or directory。
  解决方法:修改configure文件,删除$RM “$cfgfile”这一行(在19744行)。重新再运行./configure就可以了。
  看了下configure文件,其实可以忽略这个错。configure文件中cfgfile=”${ofile}T”定义的这里变量值是不存在的(${ofile}T的值为libtoolT),最后所以报错了。

  2、编译安装PHP 5.3.6(FastCGI模式)
  从PHP 5.3.3开始就已经集成了PHP-FPM,所以这里就不用再打PHP-FPM的补丁了。更多PHP-FPM相关资料可参考:什么是CGI、FastCGI、PHP-CGI、PHP-FPM、Spawn-FCGI?

tar xvf php-5.3.6.tar.gz
cd php-5.3.6
 
./configure --prefix=/usr/local/php --with-config-file-path=/usr/local/php/etc \
--with-mysql=/usr/local/mysql --with-mysqli=/usr/local/mysql/bin/mysql_config \
--with-iconv-dir=/usr/local --with-freetype-dir --with-jpeg-dir --with-png-dir --with-zlib \
--with-libxml-dir=/usr --enable-xml --disable-rpath  --enable-safe-mode --enable-bcmath \
--enable-shmop --enable-sysvsem --enable-inline-optimization --with-curl --with-curlwrappers \
--enable-mbregex  --enable-fpm  --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
 
make ZEND_EXTRA_LIBS='-liconv'
make install
cd ..
 

 编译最后可能会提示:PEAR package PHP_Archive not installed: generated phar will require PHP’s phar extension be enabled.这说明没有安装PEAR。更多可参考:Pecl和Pear的区别和联系?
  解决方法:
  1、加入–without-pear参数,不安装PEAR。
  2、安装PHP后,再通过PHAR安装PEAR。

wget http://pear.php.net/go-pear.phar
/usr/local/php/bin/php go-pear.phar
创建PHP的配置文件
 


cp -f php.ini-production /usr/local/php/etc/php.ini
 

  3、编译安装PHP5扩展模块
  Memcache扩展
  Memcache是danga.com的一个开源项目,它是一个高性能的分布式的内存对象缓存系统,通过在内存里维护一个统一的巨大的Hash表,能够用来存储各种格式的数据。可以类比于MySQL这样的服务,而PHP扩展的Memcache实际上是连接Memcache的方式。

tar xvf memcache-2.2.6.tgz
cd memcache-2.2.6
/usr/local/php/bin/phpize
./configure --with-php-config=/usr/local/php/bin/php-config
make
make install
cd ../
 

eaccelerator加速器
  eaccelerator是一个自由开放源码PHP加速器,优化和动态内容缓存,提高了性能php脚本的缓存性能,使得PHP脚本在编译的状态下,对服务器的开销几乎完全消除。 它还有对脚本起优化作用,以加快其执行效率。使您的PHP程序代码执效率能提高1-10倍;

tar jxvf eaccelerator-0.9.6.1.tar.bz2
cd eaccelerator-0.9.6.1/
/usr/local/php/bin/phpize
./configure --enable-eaccelerator=shared --with-php-config=/usr/local/php/bin/php-config
make
make install
cd ..
 

PDO_MYSQL
 
  PDO_MYSQL是一个驱动程序,它实现了PHP数据对象(PDO)的接口,以实现从PHP访问MySQL的3.x,4.x和5.x的数据库。

tar zxvf PDO_MYSQL-1.0.2.tgz
cd PDO_MYSQL-1.0.2/
/usr/local/php/bin/phpize
./configure --with-php-config=/usr/local/php/bin/php-config --with-pdo-mysql=/usr/local/mysql
make
make install
cd ..
 

ImageMagick
  ImageMagick是一套稳定的工具集和开发包,可以用来读、写和处理超过89种基本格式的图片文件,包括流行的TIFF, JPEG, GIF, PNG, PDF以及PhotoCD等格式.

tar xvf ImageMagick-6.6.9-9.tar.gz
cd ImageMagick-6.6.9-9
./configure
make
make install
cd ..
 

Imagick
  Imagick(PHP的原生函数库)是一个功能强大的图像处理库,Imagick是PHP下针对ImageMagick这个强大软件包的API接口。Imagick依赖于ImageMagick.

tar zxvf imagick-3.0.0.tgz
cd imagick-3.0.0/
/usr/local/php/bin/phpize
./configure --with-php-config=/usr/local/php/bin/php-config
make
make install
cd ..
 

  4、修改PHP.INI

sed -i 's#; extension_dir = "./"#extension_dir = "/usr/local/php/lib/php/extensions/no-debug-non-zts-20090626/"\nextension = "memcache.so"\nextension = "pdo_mysql.so"\nextension = "imagick.so"\n#' /usr/local/php/etc/php.ini
sed -i "s#;always_populate_raw_post_data = On#always_populate_raw_post_data = On#g" /usr/local/php/etc/php.ini
sed -i "s#;cgi.fix_pathinfo=1#cgi.fix_pathinfo=0#g" /usr/local/php/etc/php.ini
 

     5、配置eAccelerator加速PHP:
      创建缓存存放目录

mkdir -p /usr/local/eaccelerator_cache
vi /usr/local/php/etc/php.ini
 

       按shift+g键跳到配置文件的最末尾,加上以下配置信息:

[eaccelerator]
zend_extension="/usr/local/php/lib/php/extensions/no-debug-non-zts-20090626/eaccelerator.so"
eaccelerator.shm_size="64"
eaccelerator.cache_dir="/usr/local/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"
 

    6、建立存放日志的目录
mkdir -p /usr/local/php/logs

   7、创建php-fpm配置文件

[eaccelerator]
vi  /usr/local/php/etc/php-fpm.conf
 
[global]
pid = /usr/local/php/logs/php-fpm.pid
error_log = /usr/local/php/logs/php-fpm.log
log_level = notice
emergency_restart_threshold = 10
emergency_restart_interval = 1m
process_control_timeout = 5s
daemonize = yes
[www]
listen = 127.0.0.1:9000
listen.backlog = -1
listen.allowed_clients = 127.0.0.1
user = www
group = www
listen.mode=0666
pm = static
pm.max_children = 64
pm.start_servers = 20
pm.min_spare_servers = 5
pm.max_spare_servers = 35
pm.max_requests = 1024
 
request_terminate_timeout = 0s
request_slowlog_timeout = 0s
slowlog = logs/slow.log
rlimit_files = 65535
rlimit_core = 0
chroot =
chdir =
catch_workers_output = yes
env[HOSTNAME] = $HOSTNAME
env[PATH] = /usr/local/bin:/usr/bin:/bin
env[TMP] = /tmp
env[TMPDIR] = /tmp
env[TEMP] = /tmp
 
php_flag[display_errors] = off
 

8、启动php-cgi进程
  启动前可先测试下php-fpm.conf的语法是否正确。如出现下面的提示,表示没有问题。

/usr/local/php/sbin/php-fpm -t
[18-Apr-2011 19:53:51] NOTICE: configuration file /usr/local/php/etc/php-fpm.conf test is successful
 

启动php-cgi进程后,检听的是127.0.0.1的9000端口,进程数为64(如果服务器内存小于3GB,可以只开启64个进程),用户为www
/usr/local/php/sbin/php-fpm

注:运行php-fpm前,记得先建立www用户,不然运行后会报错。因为PHP-FPM配置文件中是用www来运行的。
四、安装Nginx 1.0.0
  1、创建相关用户和目录
  创建www用户和组,以及供blog和www两个虚拟主机使用的目录:

/usr/sbin/groupadd www
/usr/sbin/useradd -g www www
mkdir -p /data/www/htdocs/blog
chmod +w /data/www/htdocs/blog
chown -R www:www /data/www/htdocs/blog
mkdir -p /data/www/htdocs/www
chmod +w /data/www/htdocs/www
chown -R www:www /data/www/htdocs/www
 

创建Nginx日志目录

mkdir -p /data1/logs
chmod +w /data1/logs
chown -R www:www /data1/logs
 

2、安装Nginx所需的pcre库

tar zxvf pcre-8.12.tar.gz
cd pcre-8.12/
./configure
make && make install
cd ..
 

3、安装Nginx

tar xvf nginx-1.0.0.tar.gz
cd nginx-1.0.0/
./configure --user=www --group=www --prefix=/usr/local/nginx --with-http_stub_status_module --with-http_ssl_module
make && make install
cd ..
 

4、创建Nginx配置文件
  在/usr/local/nginx/conf/目录中创建nginx.conf文件:

rm -f /usr/local/nginx/conf/nginx.conf
vi /usr/local/nginx/conf/nginx.conf
 
  输入以下内容:
 
user  www www;
 
worker_processes 8;
 
error_log  /data1/logs/nginx_error.log  crit;
 
pid        /usr/local/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       8080;
    server_name  192.168.1.106;
    index index.html index.htm index.php;
    root  /data/www/htdocs/blog;
 
    #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  /data1/logs/access_blog.log  access;
      }
 
  server
  {
    listen       80;
    server_name  192.168.1.106;
    index index.html index.htm index.php;
    root  /data/www/htdocs/www;
 
    location ~ .*\.(php|php5)?$
    {    
      #fastcgi_pass  unix:/tmp/php-cgi.sock;
      fastcgi_pass  127.0.0.1:9000;
      fastcgi_index index.php;
      include fcgi.conf;
    }
 
    log_format  wwwlogs  '$remote_addr - $remote_user [$time_local] "$request" '
               '$status $body_bytes_sent "$http_referer" '
               '"$http_user_agent" $http_x_forwarded_for';
    access_log  /data1/logs/access_www.log  wwwlogs;
  }
 
  server
  {
    listen  8888;
    server_name  192.168.1.106;
 
    location / {
    stub_status on;
    access_log   off;
    }
  }
}
 

5、创建fcgi.conf文件
  在/usr/local/nginx/conf/目录中创建fcgi.conf文件:

vi /usr/local/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;
 

  6、启动Nginx
  检查Nginx配置是否正确,出现以下类似信息表示配置正确。

/usr/local/nginx/sbin/nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
 

设置可打开文件数并启动Nginx

ulimit -SHn 65535
/usr/local/nginx/sbin/nginx
 

 7、配置开机自动启动Nginx + PHP
  在/etc/rc.local末尾增加以下内容:

vi /etc/rc.local
ulimit -SHn 65535
/usr/local/php/sbin/php-fpm
/usr/local/nginx/sbin/nginx
 

  8、测试是否支持php

cd /data/www/htdocs/www/
echo "<?php phpinfo(); ?>" > phpinfo.php
 

浏览http://192.168.168.185/phpinfo.php,可以正常看到php的相关信息,扩展支持情况。

五、优化Linux内核参数
  在/etc/sysctl.conf末尾增加以下内容(可根据服务器实际情况进行调整)

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_reuse = 1

net.ipv4.tcp_mem = 94500000 915000000 927000000
net.ipv4.tcp_max_orphans = 3276800
net.ipv4.ip_local_port_range = 1024  65535
#net.ipv4.ip_conntrack_max = 10000

各内核参数含义
  net.ipv4.tcp_max_syn_backlog
  记录的那些尚未收到客户端确认信息的连接请求的最大值。对于超过128M内存的系统而言,缺省值是1024,低于128M小内存的系统则是128。
  SYN Flood攻击利用TCP协议散布握手的缺陷,伪造虚假源IP地址发送大量TCP-SYN半打开连接到目标系统,最终导致目标系统Socket队列资源耗尽而无法接受新的连接。为了应付这种攻击,现代Unix系统中普遍采用多连接队列处理的方式来缓冲(而不是解决)这种攻击,是用一个基本队列处理正常的完全连接应用(Connect()和Accept() ),是用另一个队列单独存放半打开连接。
  这种双队列处理方式和其他一些系统内核措施(例如Syn-Cookies/Caches)联合应用时,能够比较有效的缓解小规模的SYN Flood攻击(事实证明<1000p/s)加大SYN队列长度可以容纳更多等待连接的网络连接数,一般遭受SYN Flood攻击的网站,都存在大量SYN_RECV状态,所以调大tcp_max_syn_backlog值能增加抵抗syn攻击的能力。
  net.core.netdev_max_backlog
  每个网络接口接收数据包的速率比内核处理这些包的速率快时,允许送到队列的数据包的最大数目。
  net.core.somaxconn
  调整系统同时发起并发TCP连接数,可能需要提高连接储备值,以应对大量突发入局连接请求的情况。 如果同时接收到大量连接请求,使用较大的值会提高受支持的暂挂连接的数量,从而可减少连接失败的数量。大的侦听队列对防止DDoS攻击也会有所帮助。挂起请求的最大数量默认是128。
  net.core.wmem_default
  该参数指定了发送套接字缓冲区大小的缺省值(以字节为单位)
  net.core.rmem_default
  该参数指定了接收套接字缓冲区大小的缺省值(以字节为单位)
  net.core.rmem_max
  该参数指定了接收套接字缓冲区大小的最大值(以字节为单位)
  net.core.wmem_max
  该参数指定了发送套接字缓冲区大小的最大值(以字节为单位)

net.ipv4.tcp_timestamps
  Timestamps可以防范那些伪造的sequence号码。一条1G的宽带线路或许会重遇到带out-of-line数值的旧sequence号码(假如它是由于上次产生的)。时间戳能够让内核接受这种“异常”的数据包。这里需要将其关掉,以提高性能。
  net.ipv4.tcp_synack_retries
  对于远端的连接请求SYN,内核会发送SYN+ACK数据报,以确认收到上一个SYN连接请求包。这是所谓的三次握手(threeway handshake)机制的第二个步骤。这里决定内核在放弃连接之前所送出的SYN+ACK数目。不应该大于255,默认值是5,对应于180秒左右时间。(可以根据tcp_syn_retries来决定这个值)
  net.ipv4.tcp_syn_retries
  对于一个新建连接,内核要发送多少个SYN连接请求才决定放弃。不应该大于255,默认值是5,对应于180秒左右时间。(对于大负载而物理通信良好的网络而言,这个值偏高,可修改为2.这个值仅仅是针对对外的连接,对进来的连接,是由tcp_retries1 决定的)
  net.ipv4.tcp_tw_recycle
  表示开启TCP连接中TIME-WAIT Sockets的快速回收,默认为0,表示关闭。
  net.ipv4.tcp_tw_reuse
  表示开启重用,允许将TIME-WAIT Sockets重新用于新的TCP连接,默认为0,表示关闭。这个对快速重启动某些服务,而启动后提示端口已经被使用的情形非常有帮助。
  net.ipv4.tcp_mem
  tcp_mem有3个INTEGER变量:low, pressure, high
  low:当TCP使用了低于该值的内存页面数时,TCP没有内存压力,TCP不会考虑释放内存。(理想情况下,这个值应与指定给tcp_wmem的第2个值相匹配。这第2个值表明,最大页面大小乘以最大并发请求数除以页大小 (131072*300/4096)
  pressure:当TCP使用了超过该值的内存页面数量时,TCP试图稳定其内存使用,进入pressure模式,当内存消耗低于low值时则退出pressure状态。(理想情况下这个值应该是TCP可以使用的总缓冲区大小的最大值(204800*300/4096)
  high:允许所有TCP Sockets用于排队缓冲数据报的页面量。如果超过这个值,TCP连接将被拒绝,这就是为什么不要令其过于保守(512000*300/4096)的原因了。在这种情况下,提供的价值很大,它能处理很多连接,是所预期的2.5倍;或者使现有连接能够传输2.5倍的数据。
  一般情况下这些值是在系统启动时根据系统内存数量计算得到的。
  net.ipv4.tcp_max_orphans
  系统所能处理不属于任何进程的TCP sockets最大数量。假如超过这个数量﹐那么不属于任何进程的连接会被立即reset,并同时显示警告信息。之所以要设定这个限制﹐纯粹为了抵御那些简单的DoS攻击﹐千万不要依赖这个或是人为的降低这个限制
  net.ipv4.ip_local_port_range
  将系统对本地端口范围限制设置为1024~65000之间
  net.ipv4.ip_conntrack_max = 10000
  设置系统对最大跟踪的TCP连接数的限制(CentOS 5.6无此参数)
  使配置立即生效:

/sbin/sysctl -p
 


六、用Webbench进行简单的压力测试
  Webbench是有名的网站压力测试工具。Webbench支持多平台,FreeBSD、Linux、Windows都可以使用。Webbench最多可以模拟3万个并发连接去测试网站的负载能力。
  
  1、Webbench安装

wget http://home.tiscali.cz/~cz210552/distfiles/webbench-1.5.tar.gz
tar zxvf webbench-1.5.tar.gz
cd webbench-1.5
make && make install
在编译webbench的时候可能会出现下面类似的错误:
ctags *.c
/bin/sh: ctags: command not found
make: [tags] Error 127 (ignored)
  解决方法:由于是缺少ctags组件,安装后即可。
yum -y –disablerepo=\* –enablerepo=c5-media install ctags
  2、使用:
 


<div>::CODECOLORER_BLOCK_53::</div>

参数说明:-c表示并发数,-t表示时间()
  3、测试结果示例:
Webbench – Simple Web Benchmark 1.5
Copyright (c) Radim Kolar 1997-2004, GPL Open Source Software.
Benchmarking: GET <a href="http://192.168.1.106/phpinfo.php">http://192.168.1.106/phpinfo.php</a>
500 clients, running 30 sec.
Speed=39824 pages/min, 37963652 bytes/sec.
Requests: 19912 susceed, 0 failed.
  七、在不停止Nginx服务的情况下平滑变更Nginx配置
  平滑重启
  1、对于Nginx 0.8.x以上的版本,平滑重启Nginx配置非常简单,执行以下命令即可:
 


<div>::CODECOLORER_BLOCK_54::</div>

2、对于Nginx 0.8.x之前的版本,按照以下步骤进行即可。
 


<div>::CODECOLORER_BLOCK_55::</div>

八、Nginx支持的信号
  1、TERM,INT 快速关闭
  2、QUIT 从容关闭
  3、HUP 平滑重启,重新加载配置文件
  4、USR1 重新打开日志文件,在切割日志时用处比较大
  5、USR2 平滑升级可执行程序
  6、WINCH 从容关闭工作进程
 


vi /usr/local/nginx/sbin/cut_nginx_log.sh
 
#!/bin/bash
# This script run at 00:00
 
# The Nginx logs path
logs_path="/data1/logs/"
 
mkdir -p ${logs_path}$(date -d "yesterday" +"%Y")/$(date -d "yesterday" +"%m")/
mv ${logs_path}access_blog.log ${logs_path}$(date -d "yesterday" +"%Y")/$(date -d "yesterday" +"%m")/access_blog_$(date -d "yesterday" +"%Y%m%d").log
mv ${logs_path}access_www.log ${logs_path}$(date -d "yesterday" +"%Y")/$(date -d "yesterday" +"%m")/access_www_$(date -d "yesterday" +"%Y%m%d").log
kill -USR1 `cat /usr/local/nginx/nginx.pid`
 

2、设置crontab,每天凌晨00:00切割nginx访问日志

crontab -e
 

输入以下内容:

00 00 * * * /bin/bash  /usr/local/nginx/sbin/cut_nginx_log.sh
 

方法二
  1、创建脚本/usr/local/nginx/sbin/cut_nginx_log.sh

vi /usr/local/nginx/sbin/cut_nginx_log.sh
 
#!/bin/bash
 
nginx_app=/usr/local/nginx/sbin/nginx  #设置nginx的目录
logs_dir=/data1/logs/ #log目录
bak_dir=/data1/logs/bak/ #log备份目录
 
#先把现有的log文件挪到备份目录临时存放
cd $logs_dir
echo “moving logs”
/bin/mv *.log $bak_dir
sleep 3
 
#重建nginx log
echo “rebuild logs”
echo “$nginx_app -s reopen”
$nginx_app -s reopen
 
#按天打包log文件
echo “begining of tar”
cd $bak_dir
/bin/tar czf `date +%Y%m%d`.tgz *.log
 
#删除备份目录的临时文件
echo “rm logs”
rm -f *.log
echo “done”
 

2、设置crontab,每天凌晨00:00切割nginx访问日志

crontab -e
 


00 00 * * * /bin/bash  /usr/local/nginx/sbin/cut_nginx_log.sh>/dev/null 2>&1
 


方法三:
  1、这种方法是通过logrotate实现的,先创建logrotate所需的脚本。

/data1/logs/*.log {
       daily
       missingok
       rotate 7
       compress
       delaycompress
       notifempty
       create 640 root adm
       sharedscripts
       postrotate
               [ ! -f /usr/local/nginx/nginx.pid ] || kill -USR1 `cat /usr/local/nginx/nginx.pid`
       endscript
}

2、手工测试下看能否正常轮询

logrotate -vf  /etc/logrotate.conf
有趣的视频娱乐一下

原文链接:http://www.webzone8.com/article/333.html

用户评论

用户【31.184.236*****】说:&lt;a href=&quot;http://torontoadrugstore.ru/&quot;&gt;onlinepharmacy&lt;/a&gt; &lt;a href=&quot;http://onlinepharmaciesacanada.ru/&quot;&gt;canadian online pharmacy&lt;/a&gt; &lt;a href=&quot;http://onlinepharmacyawithoutaprescription.ru/&quot;&gt;paxil canada pharmacy no perscription&lt;/a&gt; &lt;a href=&quot;http://canadianonlineapharmacy.ru/&quot;&gt;canadian pharmacy cialis 20mg&lt;/a&gt; &lt;a href=&quot;http://freecialisasamples.ru/&quot;&gt;cialis canada&lt;/a&gt; &lt;a href=&quot;http://viagrawithoutaprescriptions.ru/&quot;&gt;viagra without prescriptions&lt;/a&gt; &lt;a href=&quot;http://onlinepharmaciesa.ru/&quot;&gt;canada pharmacy&lt;/a&gt; &lt;a href=&quot;http://bestprice100mgaviagra.ru/&quot;&gt;lowest prices on viagra&lt;/a&gt; &lt;a href=&quot;http://cialisa40mg.ru/&quot;&gt;cialis professional 20 mg germany&lt;/a&gt; &lt;a href=&quot;http://viagraasamples.ru/&quot;&gt;generic viagra sample pack&lt;/a&gt;

用户【195.184.20*****】说:Будущей маме существенно знать, что предпочтение роддома надо начинать с задачи о плановой мойке. А цепочка анализов для женщин в положении производят бесплатно при наличии направления от доктора. Нужная и актуальная информация разрешит сберечь на обследовании и родах. Не ожидайте, что в женской консультации все сообщат. Удивите гинеколога вопросом о потенциале вашего областного перинатального центра. Удачная беременность и роды – заслуга будущей матери, которая представляет личные права. [url=http://mamatam.ru/pervouralskij-roddom-vyplatit-rozhenice-bolee-milliona-rublej]первоуральский роддом[/url]

用户【88.119.160*****】说:Whats Taking place im new to this, I stumbled upon this I have discovered It absolutely useful and it has helped me out loads.I hope to give a contribution &amp; assist different users like its helped me. nice job.

用户【31.184.236*****】说:&lt;a href=&quot;http://canadianhealthandcaremallscam.com/&quot;&gt;canadian health and care mall&lt;/a&gt; &lt;a href=&quot;http://canadianpharmacyonlinewithoutscript.com/&quot;&gt;canada pharmacy online&lt;/a&gt; &lt;a href=&quot;http://northwestpharmacycanadaprescriptions.com/&quot;&gt;northwestern canada drugs&lt;/a&gt; &lt;a href=&quot;http://northwestpharmacyca.com/&quot;&gt;best pharmacy in canada&lt;/a&gt; &lt;a href=&quot;http://supremesuppliersmumbai.com/&quot;&gt;order cipro online supreme suppliers&lt;/a&gt; &lt;a href=&quot;http://supremesuppliersindia.com/&quot;&gt;canadian pharmacy cialis&lt;/a&gt; &lt;a href=&quot;http://edmedicationsonlinebuy.com/&quot;&gt;e.d.pills&lt;/a&gt; &lt;a href=&quot;http://cialisfreesamples.com/&quot;&gt;cialis sample&lt;/a&gt;

用户【31.184.236*****】说:&lt;a href=&quot;http://medsfromindia.ru/&quot;&gt;viagra from india&lt;/a&gt; &lt;a href=&quot;http://flagyltablets.ru/&quot;&gt;where can i buy flagyl 500mg&lt;/a&gt; &lt;a href=&quot;http://stendracost.ru/&quot;&gt;stendra sale&lt;/a&gt; &lt;a href=&quot;http://prescriptionsonline.ru/&quot;&gt;cialis without a doctors prescription&lt;/a&gt; &lt;a href=&quot;http://kamagragold100mgreview.ru/&quot;&gt;kamagra gold 100mg review&lt;/a&gt; &lt;a href=&quot;http://pharmacyrxworld.ru/&quot;&gt;rx4u pharmacy&lt;/a&gt; &lt;a href=&quot;http://xenicalorlistatbuyonlineusa.ru/&quot;&gt;buy xenical and reductil&lt;/a&gt; &lt;a href=&quot;http://comprarcialisencanada.ru/&quot;&gt;achat en ligne cialis canada&lt;/a&gt; &lt;a href=&quot;http://viagrasuperactive150mg.ru/&quot;&gt;buy super active viagra online free&lt;/a&gt; &lt;a href=&quot;http://cialisonlineusa.ru/&quot;&gt;cialis online canada&lt;/a&gt; &lt;a href=&quot;http://bestprice100mggenericviagra.ru/&quot;&gt;best prices for viagra 100mg&lt;/a&gt;

用户【31.184.236*****】说:&lt;a href=&quot;http://maxifortzimax100mg.com/&quot;&gt;maxifort 50 mg&lt;/a&gt;

用户【31.184.236*****】说:&lt;a href=&quot;http://cialisorderbymail.com/&quot;&gt;buy generic cialis&lt;/a&gt;

用户【31.184.236*****】说:&lt;a href=&quot;http://fastviagra.net/&quot;&gt;fast delivery generic viagra&lt;/a&gt;

用户【31.184.236*****】说:&lt;a href=&quot;http://northwestpharmacycanadaprescriptions.com/&quot;&gt;my canadian pharmacy corp&lt;/a&gt;

用户【31.184.236*****】说:&lt;a href=&quot;http://canadianpharmaciesmailorder.com/&quot;&gt;canadian pharmacies mail order&lt;/a&gt;

用户【31.184.236*****】说:&lt;a href=&quot;http://fastviagra.net/&quot;&gt;best price viagra 100mg costco&lt;/a&gt; &lt;a href=&quot;http://pfizerbrandviagra.net/&quot;&gt;pfizer brand viagra&lt;/a&gt; &lt;a href=&quot;http://cialisorderbymail.com/&quot;&gt;order cialis from india&lt;/a&gt; &lt;a href=&quot;http://canadianpharmaciesmailorder.com/&quot;&gt;canadian pharmacy&lt;/a&gt; &lt;a href=&quot;http://maxifortzimax100mg.com/&quot;&gt;maxifort zimax sildenafil 50 mg&lt;/a&gt;

用户【31.184.236*****】说:&lt;a href=&quot;http://supremesuppliers.ru/&quot;&gt;supreme suppliers&lt;/a&gt;

用户【31.184.236*****】说:&lt;a href=&quot;http://rxexpressonline.ru/&quot;&gt;pharmacyrxone&lt;/a&gt;

用户【31.184.236*****】说:&lt;a href=&quot;http://buymetoprololwithoutaprescription.ru/&quot;&gt;ventolin hfa aer glaxosmith&lt;/a&gt;

用户【31.184.236*****】说:&lt;a href=&quot;http://cialiswithdapoxetine.ru/&quot;&gt;cialis dapoxetine overnight shipping&lt;/a&gt;

12345678910...22下一页

发表评论

姓名:*
邮箱:*
网站:*