nginx 負載均衡配置

Nginx
Nginx ("engine x") 是一個高性能的 HTTP 和 反向代理 服務器,也是一個 IMAP/POP3/SMTP 代理服務器。
第一個公開版本0.1.0發佈於2004年10月4日。
其將源代碼以類BSD許可證的形式發佈,因它的穩定性、豐富的功能集、示例配置文件和低系統資源的消耗而聞名。
2011年6月1日,nginx 1.0.4發佈。
Nginx是一款輕量級的Web 服務器/反向代理服務器及電子郵件(IMAP/POP3)代理服務器,
並在一個BSD-like 協議下發行。由俄羅斯的程序設計師Igor Sysoev所開發,
其特點是佔有內存少,併發能力強,事實上nginx的併發能力確實在同類型的網頁服務器中表現較好,中國大陸使用nginx網站用戶有:新浪、網易、騰訊等。




功能:
web服務器
web reverse proxy
smtp reverse proxy


安裝之前準備
1、依賴 gcc openssl-devel pcre-devel zlib-devel
安裝:yum install gcc openssl-devel pcre-devel zlib-devel 
2、創建用戶和用戶組。爲了方便nginx運行而不影響linux安全
創建組:groupadd -r nginx
創建用戶:useradd -r -g nginx  -M nginx 
-M 表示不創建用戶的家目錄。


安裝Nginx
./configure \
  --prefix=/usr \
  --sbin-path=/usr/sbin/nginx \
  --conf-path=/etc/nginx/nginx.conf \
  --error-log-path=/var/log/nginx/error.log \
  --http-log-path=/var/log/nginx/access.log \
  --pid-path=/var/run/nginx/nginx.pid  \
  --lock-path=/var/lock/nginx.lock \
  --user=nginx \
  --group=nginx \
  --with-http_ssl_module \
  --with-http_flv_module \
  --with-http_stub_status_module \
  --with-http_gzip_static_module \
  --http-client-body-temp-path=/var/tmp/nginx/client/ \
  --http-proxy-temp-path=/var/tmp/nginx/proxy/ \
  --http-fastcgi-temp-path=/var/tmp/nginx/fcgi/ \
  --http-uwsgi-temp-path=/var/tmp/nginx/uwsgi \
  --http-scgi-temp-path=/var/tmp/nginx/scgi \
  --with-pcre


  make && make install


  配置Nginx爲系統服務,以方便管理
  1、在/etc/rc.d/init.d/目錄中建立文本文件nginx
  2、在文件中粘貼下面的內容:
#!/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' -`
   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


3、修改nginx文件的執行權限
chmod +x nginx
4、添加該文件到系統服務中去
chkconfig --add nginx
查看是否添加成功
chkconfig --list nginx


啓動,停止,重新裝載
service nginx start|stop




nginx是多進程,主從結構。一個主(master)進程多個從(worker)進程




配置文件




#運行用戶
user nobody;
#啓動進程,通常設置成和cpu(核心)的數量相等
worker_processes  1;


#全局錯誤日誌及PID文件
#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;


#pid        logs/nginx.pid;


#工作模式及連接數上限
events {
    #epoll是多路複用IO(I/O Multiplexing)中的一種方式,
    #僅用於linux2.6以上內核,可以大大提高nginx的性能
    use   epoll; 


    #單個後臺worker process進程的最大併發鏈接數    
    worker_connections  1024;


    # 併發總數是 worker_processes 和 worker_connections 的乘積
    # 即 max_clients = worker_processes * worker_connections
    # 在設置了反向代理的情況下,max_clients = worker_processes * worker_connections / 4  爲什麼
    # 爲什麼上面反向代理要除以4,應該說是一個經驗值
    # 根據以上條件,正常情況下的Nginx Server可以應付的最大連接數爲:4 * 8000 = 32000
    # worker_connections 值的設置跟物理內存大小有關
    # 因爲併發受IO約束,max_clients的值須小於系統可以打開的最大文件數
    # 而系統可以打開的最大文件數和內存大小成正比,一般1GB內存的機器上可以打開的文件數大約是10萬左右
    # 我們來看看360M內存的VPS可以打開的文件句柄數是多少:
    # $ cat /proc/sys/fs/file-max
    # 輸出 34336
    # 32000 < 34336,即併發連接總數小於系統可以打開的文件句柄總數,這樣就在操作系統可以承受的範圍之內
    # 所以,worker_connections 的值需根據 worker_processes 進程數目和系統可以打開的最大文件總數進行適當地進行設置
    # 使得併發總數小於操作系統可以打開的最大文件數目
    # 其實質也就是根據主機的物理CPU和內存進行配置
    # 當然,理論上的併發總數可能會和實際有所偏差,因爲主機還有其他的工作進程需要消耗系統資源。
    # ulimit -SHn 65535


}




http {
    #設定mime類型,類型由mime.type文件定義
    include    mime.types;
    default_type  application/octet-stream;
    #設定日誌格式
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';


    access_log  logs/access.log  main;


    #sendfile 指令指定 nginx 是否調用 sendfile 函數(zero copy 方式)來輸出文件,
    #對於普通應用,必須設爲 on,
    #如果用來進行下載等應用磁盤IO重負載應用,可設置爲 off,
    #以平衡磁盤與網絡I/O處理速度,降低系統的uptime.
    sendfile     on;
    #tcp_nopush     on;


    #連接超時時間
    #keepalive_timeout  0;
    keepalive_timeout  65;
    tcp_nodelay     on;


    #開啓gzip壓縮
    gzip  on;
    gzip_disable "MSIE [1-6].";


    #設定請求緩衝
    client_header_buffer_size    128k;
    large_client_header_buffers  4 128k;




    #設定虛擬主機配置
    server {
        #偵聽80端口
        listen    80;
        #定義使用 www.nginx.cn訪問
        server_name  www.nginx.cn;


        #定義服務器的默認網站根目錄位置
        root html;


        #設定本虛擬主機的訪問日誌
        access_log  logs/nginx.access.log  main;


        #默認請求
        location / {
            
            #定義首頁索引文件的名稱
            index index.php index.html index.htm;   


        }


        # 定義錯誤提示頁面
        error_page   500 502 503 504 /50x.html;
        location = /50x.html {
        }


        #靜態文件,nginx自己處理
        location ~ ^/(images|javascript|js|css|flash|media|static)/ {
            
            #過期30天,靜態文件不怎麼更新,過期可以設大一點,
            #如果頻繁更新,則可以設置得小一點。
            expires 30d;
        }


        #PHP 腳本請求全部轉發到 FastCGI處理. 使用FastCGI默認配置.
        location ~ .php$ {
            fastcgi_pass 127.0.0.1:9000;
            fastcgi_index index.php;
            fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
            include fastcgi_params;
        }


        #禁止訪問 .htxxx 文件
            location ~ /.ht {
            deny all;
        }


    }
}






htttp{


server{
#表示一個虛擬主機
}
}


location 映射
location [ = | ~ | ~* | ^~ ] uri { ... }


location URI {}:
對當前路徑及子路徑下的所有對象都生效;


location = URI {}: 必須執行一個具體文件路徑(不能使用目錄)
精確匹配指定的路徑,不包括子路徑,因此,只對當前資源生效;


location ~ URI {}:
location ~* URI {}:
模式匹配URI,此處的URI可使用正則表達式,~區分字符大小寫,~*不區分字符大小寫;


location ^~ URI {}:
不使用正則表達式


優先級:= > ^~ > ~|~* >  /|/dir/


訪問控制
IP訪問控制
location  {
  deny  IP /IP段
  deny  192.168.1.109;
  allow 192.168.1.0/24;
}

用戶認證訪問

模塊ngx_http_auth_basic_module 允許使用“HTTP基本認證”協議驗證用戶名和密碼來限制對資源的訪問。
location / {
auth_basic           "closed site";
auth_basic_user_file /var/users;
    }
Apache發行包中的htpasswd命令來創建user_file 文件
htpasswd -c -m /var/users username

autoindex 在瀏覽器中列出當前目錄的文件索引
autoindex  on;


啓用訪問狀態模塊
 location /status{
stub_status on;
 }


虛擬主機
  一個server{} 就是一個虛擬主機 
  基於域名




反向代理:
proxy_pass


1、自動監測當機
2、自動心跳


upstream  名字 {
  server  IP:PORT;
  server  IP:PORT;



server {
  location  /  {
proxy_pass http://名字;
  
  }


}




location [op] URI {
   proxy_pass http://192.168.100.11/;
}
比如:
location /forum/ {
proxy_pass http://172.16.100.11:8080/bbs/;
}




http://www.bjsxt.com/forum/
--> http://172.16.100.11:8080/bbs/;


location ~* ^/forum {
proxy_pass http://172.16.100.11:8080;
}


http://www.bjsxt.com/forum/ -->
http://172.16.100.11:8080/forum/


改變反向代理時,apache記錄的日誌


httpd.conf
  LogFormat %{X-Real_IP}i
  
作業






2、使用nginx完成SEO中的,動態網頁靜態化。
http://192.168.239.3/test.action?id=1
http://192.168.239.3/test.action?id=2
http://192.168.239.3/test.action?id=3


3、自學apache反向代理和負載均衡(wrr)。
  


靜態化


hash   consisten_hash $remote_addr  根據客戶端ip映射   consistent_hash $uri 根據客戶端請求的uri映射  consisten_hash  $args 根據客戶端攜帶的參數映射;


httpserver  
session一致
 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章