歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux基礎 >> 關於Linux >> Centos-6.3-x86_64minimal迷你版安裝筆記-Nginx篇

Centos-6.3-x86_64minimal迷你版安裝筆記-Nginx篇

日期:2017/3/1 13:46:45   编辑:關於Linux
安裝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
Copyright © Linux教程網 All Rights Reserved