欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Centos-6.3-x86_64 minimal 迷你版安装笔记 - Nginx 篇

程序员文章站 2024-03-11 15:38:49
...
安装Nginx 1.2.6

1、下载Nginx

# wget http://nginx.org/download/nginx-1.2.6.tar.gz

2、解压

# tar -vzxf nginx-1.2.6.tar.gz

3、编译

# ./configure --prefix=/usr/local/nginx --pid-path=/var/run/nginx.pid --error-log-path=/var/logs/nginx/error.log --http-log-path=/var/logs/nginx/access.log --with-http_stub_status_module Configuration summary + using system PCRE library + OpenSSL library is not used + md5: using system crypto library + sha1: using system crypto library + using system zlib library nginx path prefix: "/usr/local/nginx" nginx binary file: "/usr/local/nginx/sbin/nginx" nginx configuration prefix: "/usr/local/nginx/conf" nginx configuration file: "/usr/local/nginx/conf/nginx.conf" nginx pid file: "/var/run/nginx.pid" nginx error log file: "/var/logs/nginx/error.log" nginx http access log file: "/var/logs/nginx/access.log" nginx http client request body temporary files: "client_body_temp" nginx http proxy temporary files: "proxy_temp" nginx http fastcgi temporary files: "fastcgi_temp" nginx http uwsgi temporary files: "uwsgi_temp" nginx http scgi temporary files: "scgi_temp" # make # sudo make install

4、修改配置

# sudo vim /usr/local/nginx/conf/nginx.conf

5、启动、重启、关闭

运行 prefix/sbin/nginx
启动
# sudo /usr/local/nginx/sbin/nginx
重启配置(修改配置后使得配置生效)
# sudo kill -HUP `cat /var/run/nginx.pid`
或者
# sudo /usr/local/nginx/sbin/nginx -s reload
重启Nginx
# sudo /usr/local/nginx/sbin/nginx -s reopen
关闭
# sudo kill `cat /var/run/nginx.pid`
或者
# sudo /usr/local/nginx/sbin/nginx -s quit

查看版本号
# /usr/local/nginx/sbin/nginx -v
不运行,仅测试配置文件。nginx检查正确的语法配置并且在配置中打开指定的文件
# sudo /usr/local/nginx/sbin/nginx -t
查看版本号、编译版本和配置参数
# /usr/local/nginx/sbin/nginx -V
发送stop, quit, reopen, reload信号到主进程(版本 >= 0.7.53)
# sudo /usr/local/nginx/sbin/nginx -s stop
# sudo /usr/local/nginx/sbin/nginx -s quit
# sudo /usr/local/nginx/sbin/nginx -s reopen
# sudo /usr/local/nginx/sbin/nginx -s reload

6、安装自启动程序

下载地址:http://wiki.nginx.org/InitScripts Red Hat Nginx Init Script:http://wiki.nginx.org/RedHatNginxInitScript 下载后文件为:nginx,如下:
#!/bin/sh
#
# nginx - this script starts and stops the nginx daemon
#
# chkconfig:   - 85 15 
# description:  Nginx is an HTTP(S) server, HTTP(S) reverse \
#               proxy and IMAP/POP3 proxy server
# processname: nginx
# config:      /etc/nginx/nginx.conf
# config:      /etc/sysconfig/nginx
# pidfile:     /var/run/nginx.pid
 
# Source function library.
. /etc/rc.d/init.d/functions
 
# Source networking configuration.
. /etc/sysconfig/network
 
# Check that networking is up.
[ "$NETWORKING" = "no" ] && exit 0
 
nginx="/usr/sbin/nginx"
prog=$(basename $nginx)
 
NGINX_CONF_FILE="/etc/nginx/nginx.conf"
 
[ -f /etc/sysconfig/nginx ] && . /etc/sysconfig/nginx
 
lockfile=/var/lock/subsys/nginx
 
make_dirs() {
   # make required directories
   user=`$nginx -V 2>&1 | grep "configure arguments:" | sed 's/[^*]*--user=\([^ ]*\).*/\1/g' -`
   if [ -z "`grep $user /etc/passwd`" ]; then
       useradd -M -s /bin/nologin $user
   fi
   options=`$nginx -V 2>&1 | grep 'configure arguments:'`
   for opt in $options; do
       if [ `echo $opt | grep '.*-temp-path'` ]; then
           value=`echo $opt | cut -d "=" -f 2`
           if [ ! -d "$value" ]; then
               # echo "creating" $value
               mkdir -p $value && chown -R $user $value
           fi
       fi
   done
}
 
start() {
    [ -x $nginx ] || exit 5
    [ -f $NGINX_CONF_FILE ] || exit 6
    make_dirs
    echo -n $"Starting $prog: "
    daemon $nginx -c $NGINX_CONF_FILE
    retval=$?
    echo
    [ $retval -eq 0 ] && touch $lockfile
    return $retval
}
 
stop() {
    echo -n $"Stopping $prog: "
    killproc $prog -QUIT
    retval=$?
    echo
    [ $retval -eq 0 ] && rm -f $lockfile
    return $retval
}
 
restart() {
    configtest || return $?
    stop
    sleep 1
    start
}
 
reload() {
    configtest || return $?
    echo -n $"Reloading $prog: "
    killproc $nginx -HUP
    RETVAL=$?
    echo
}
 
force_reload() {
    restart
}
 
configtest() {
  $nginx -t -c $NGINX_CONF_FILE
}
 
rh_status() {
    status $prog
}
 
rh_status_q() {
    rh_status >/dev/null 2>&1
}
 
case "$1" in
    start)
        rh_status_q && exit 0
        $1
        ;;
    stop)
        rh_status_q || exit 0
        $1
        ;;
    restart|configtest)
        $1
        ;;
    reload)
        rh_status_q || exit 7
        $1
        ;;
    force-reload)
        force_reload
        ;;
    status)
        rh_status
        ;;
    condrestart|try-restart)
        rh_status_q || exit 0
            ;;
    *)
        echo $"Usage: $0 {start|stop|status|restart|condrestart|try-restart|reload|force-reload|configtest}"
        exit 2
esac



保存到/etc/init.d/nginx
# cp nginx /etc/init.d
# sudo vim /etc/init.d/nginx (修改nginx主程序路径)
**************************************************************
......
#nginx="/usr/sbin/nginx"
nginx="/usr/local/nginx/sbin/nginx"
prog=$(basename $nginx)


#NGINX_CONF_FILE="/etc/nginx/nginx.conf"
NGINX_CONF_FILE="/usr/local/nginx/nginx/conf/nginx.conf"
......
**************************************************************


添加执行权限
# sudo chmod +x /etc/init.d/nginx


配置成nginx服务
# sudo chkconfig nginx on


查看配置结果
# sudo chkconfig --list nginx
nginx           0:关闭  1:关闭  2:启用  3:启用  4:启用  5:启用  6:关闭

7、监控Nginx并发统计

需要编译时加上--with-http_stub_status_module
修改nginx配置文件如下:
# sudo vi /usr/local/nginx/nginx/conf/nginx.conf

http {
    ...
    server {
        listen SOME.IP.ADD.RESS;
        ...
        location /nginx_status {
            stub_status on;
            access_log   off;
            #allow SOME.IP.ADD.RESS;
            #deny all;
        }
        ...
    }
    ...
}
# sudo yum install perl-rrdtool perl-libwww-perl.noarch
# wget http://kovyrin.net/files/mrtg/rrd_nginx.pl.txt
#!/usr/bin/perl
use RRDs;
use LWP::UserAgent;

# define location of rrdtool databases
my $rrd = '/opt/rrd';
# define location of images
my $img = '/opt/rrd';
# define your nginx stats URL
my $URL = "http://moviewer.com/nginx_status";

my $ua = LWP::UserAgent->new(timeout => 30);
my $response = $ua->request(HTTP::Request->new('GET', $URL));

my $requests = 0;
my $total =  0;
my $reading = 0;
my $writing = 0;
my $waiting = 0;

foreach (split(/\n/, $response->content)) {
  $total = $1 if (/^Active connections:\s+(\d+)/);
  if (/^Reading:\s+(\d+).*Writing:\s+(\d+).*Waiting:\s+(\d+)/) {
    $reading = $1;
    $writing = $2;
    $waiting = $3;
  }
  $requests = $3 if (/^\s+(\d+)\s+(\d+)\s+(\d+)/);
}

#print "RQ:$requests; TT:$total; RD:$reading; WR:$writing; WA:$waiting\n";

# if rrdtool database doesn't exist, create it
if (! -e "$rrd/nginx.rrd") {
  RRDs::create "$rrd/nginx.rrd",
        "-s 60",
	"DS:requests:COUNTER:120:0:100000000",
	"DS:total:ABSOLUTE:120:0:60000",
	"DS:reading:ABSOLUTE:120:0:60000",
	"DS:writing:ABSOLUTE:120:0:60000",
	"DS:waiting:ABSOLUTE:120:0:60000",
	"RRA:AVERAGE:0.5:1:2880",
	"RRA:AVERAGE:0.5:30:672",
	"RRA:AVERAGE:0.5:120:732",
	"RRA:AVERAGE:0.5:720:1460";
}

# insert values into rrd database
RRDs::update "$rrd/nginx.rrd",
  "-t", "requests:total:reading:writing:waiting",
  "N:$requests:$total:$reading:$writing:$waiting";

# Generate graphs
CreateGraphs("day");
CreateGraphs("week");
CreateGraphs("month");
CreateGraphs("year");

#------------------------------------------------------------------------------
sub CreateGraphs($){
  my $period = shift;
  
  RRDs::graph "$img/requests-$period.png",
		"-s -1$period",
		"-t Requests on nginx",
		"--lazy",
		"-h", "150", "-w", "700",
		"-l 0",
		"-a", "PNG",
		"-v requests/sec",
		"DEF:requests=$rrd/nginx.rrd:requests:AVERAGE",
		"LINE2:requests#336600:Requests",
		"GPRINT:requests:MAX:  Max\\: %5.1lf %S",
		"GPRINT:requests:AVERAGE: Avg\\: %5.1lf %S",
		"GPRINT:requests:LAST: Current\\: %5.1lf %Sreq/sec",
		"HRULE:0#000000";
  if ($ERROR = RRDs::error) { 
    print "$0: unable to generate $period graph: $ERROR\n"; 
  }

  RRDs::graph "$img/connections-$period.png",
		"-s -1$period",
		"-t Requests on nginx",
		"--lazy",
		"-h", "150", "-w", "700",
		"-l 0",
		"-a", "PNG",
		"-v requests/sec",
		"DEF:total=$rrd/nginx.rrd:total:AVERAGE",
		"DEF:reading=$rrd/nginx.rrd:reading:AVERAGE",
		"DEF:writing=$rrd/nginx.rrd:writing:AVERAGE",
		"DEF:waiting=$rrd/nginx.rrd:waiting:AVERAGE",

		"LINE2:total#22FF22:Total",
		"GPRINT:total:LAST:   Current\\: %5.1lf %S",
		"GPRINT:total:MIN:  Min\\: %5.1lf %S",
		"GPRINT:total:AVERAGE: Avg\\: %5.1lf %S",
		"GPRINT:total:MAX:  Max\\: %5.1lf %S\\n",
		
		"LINE2:reading#0022FF:Reading",
		"GPRINT:reading:LAST: Current\\: %5.1lf %S",
		"GPRINT:reading:MIN:  Min\\: %5.1lf %S",
		"GPRINT:reading:AVERAGE: Avg\\: %5.1lf %S",
		"GPRINT:reading:MAX:  Max\\: %5.1lf %S\\n",
		
		"LINE2:writing#FF0000:Writing",
		"GPRINT:writing:LAST: Current\\: %5.1lf %S",
		"GPRINT:writing:MIN:  Min\\: %5.1lf %S",
		"GPRINT:writing:AVERAGE: Avg\\: %5.1lf %S",
		"GPRINT:writing:MAX:  Max\\: %5.1lf %S\\n",
		
		"LINE2:waiting#00AAAA:Waiting",
		"GPRINT:waiting:LAST: Current\\: %5.1lf %S",
		"GPRINT:waiting:MIN:  Min\\: %5.1lf %S",
		"GPRINT:waiting:AVERAGE: Avg\\: %5.1lf %S",
		"GPRINT:waiting:MAX:  Max\\: %5.1lf %S\\n",

		"HRULE:0#000000";
  if ($ERROR = RRDs::error) { 
    print "$0: unable to generate $period graph: $ERROR\n"; 
  }
}


该脚本会按年、月、日、周分连接数和请求数生成统计表图片


# mv rrd_nginx.pl.txt rrd_nginx.pl
添加执行权限
# chmod +x rrd_nginx.pl
# sudo vim /etc/crontab
新增
* *     * * *   root    /home/web/download/rrd_nginx.pl
或者 crontab -e
新增上面一行即可
# sudo service crond restart


参考地址:http://kovyrin.net/2006/04/29/monitoring-nginx-with-rrdtool/

8、nginx日志分隔

保存分隔脚本为:/home/web/cron/cut_nginx_logs.sh

#!/bin/bash
#function:cut nginx log files for lnmp v0.5 and v0.6
#author: http://lnmp.org

#set the path to nginx log files
log_files_path="/var/logs/nginx"
#set nginx log files you want to cut
project_name=unknown
log_files_name=access
log_files_dir=${log_files_path}/bck/${project_name}/$(date -d "yesterday" +"%Y")/$(date -d "yesterday" +"%m")
set the path to nginx.
nginx_sbin="/etc/init.d/nginx"

############################################
#Please do not modify the following script #
############################################
mkdir -p $log_files_dir

#log_files_num=${#log_files_name[@]}

#cut nginx log files
#for((i=0;i<$log_files_num;i++));do
mv ${log_files_path}/${log_files_name}.log ${log_files_dir}/${log_files_name}_$(date -d "yesterday" +"%Y%m%d")_$(date +"%Y%m%d%H%M%S").log
#done

kill -USR1 $(cat /var/run/nginx.pid)

$nginx_sbin  force-reload

# sudo chmod +x cut_nginx_logs.sh
# crontab -e
5 0 * * *   root    /home/web/cron/cut_nginx_logs.sh
即每日凌晨0点5分执行分隔脚本

每日会自动在日志目录下生成类似如下文件:
/var/logs/nginx/bck/unknown/2013/02/access_20130222_20130223162711.log