Nginx負載均衡 大全

Nginx負載均衡是一個很神奇的技術,很多人都不能很好的掌握這個技術,今天在這裏我們向大家詳細的介紹下有關Nginx負載均衡的問題。今天小試了一下Nginx負載均衡,真是爽啊!Nginx是什麼?

Nginx (”engine x”) 是一個高性能的 HTTP 和 反向代理 服務器,也是一個 IMAP/POP3/SMTP 代理服務器。 Nginx 是由 Igor Sysoev 爲俄羅斯訪問量第二的 Rambler.ru 站點開發的,它已經在該站點運行超過兩年半了。Igor 將源代碼以類BSD許可證的形式發佈。儘管還是測試版,但是,Nginx 已經因爲它的穩定性、豐富的功能集、示例配置文件和低系統資源的消耗而聞名了。

首先是配置十分的簡單,而且功能非常強大。真是相見恨晚。先來看看配置文件怎麼寫吧

 

  1. worker_processes 1;  
  2. events {  
  3. worker_connections 1024;  
  4. }  
  5. http{  
  6. upstream myproject {  
  7. #這裏指定多個源服務器,ip:端口,80端口的話可寫可不寫  
  8. server 192.168.43.158:80;  
  9. server 192.168.41.167;  
  10. }  
  11. server {  
  12. listen 8080;  
  13. location / {  
  14. proxy_pass http://myproject;  
  15. }  
  16. }  

 

Nginx負載均衡有哪些功能呢?

如果後面的服務器其中一臺壞了,它能自動識別,更牛的是它好了之後Nginx可以馬上識別服務器A和B,如果A的響應時間爲3,B的響應時間爲1,那麼Nginx會自動調整訪問B的概率是A的3倍,真正做到Nginx負載均衡好的,安裝完成了。我在make的時候報了個錯,說HTTP Rewrite 模塊 有問題,我就

./configure –without-http_rewrite_module
然後再make,make install就可以了。

安裝好了之後新建一個配置文件,把上面的配置文件內容拷進去,當然要修改你的IP,保存爲比如 load_balance.conf然後啓動:

/usr/local/Nginx/sbin/Nginx -c load_balence.conf

由於Nginx的作者是俄國人,所以英文的文檔也不是那麼完善,對於我來說Nginx的最大優點還是配置簡單,功能強大。我曾經配過 apache-jk,那真的不是一般人能配的。太複雜了,而且只能用來做tomcat的Nginx負載均衡

 

 

我們就先看看Nginx的默認虛擬主機在用戶通過IP訪問,或者通過未設置的域名訪問(比如有人把他自己的域名指向了你的ip)的時候生效最關鍵的一點是,在server的設置裏面添加這一行:

  1. listen 80 default; 

後面的default參數表示這個是默認虛擬主機。

Nginx 禁止IP訪問這個設置非常有用。

比如別人通過ip或者未知域名訪問你的網站的時候,你希望禁止顯示任何有效內容,可以給他返回500.目前國內很多機房都要求網站主關閉空主機頭,防止未備案的域名指向過來造成麻煩。就可以這樣設置:

  1. server {  
  2. listen 80 default;  
  3. return 500;  

也可以把這些流量收集起來,導入到自己的網站,只要做以下跳轉設置就可以:

  1. server {  
  2. listen 80 default;  
  3. rewrite ^(.*) http://www.mydomain.com permanent;  

按照如上設置後,確實不能通過IP訪問服務器了,但是在應該用中出現當server_name後跟多個域名時,其中一個域名怎麼都無法訪問:

設置如下:

  1. server  
  2. {  
  3. listen 80;  
  4. server_name www.abc.com abc.com 

沒更改之前,通過server_name 中的www.abc.com abc.com均可訪問服務器,加入Nginx 禁止IP訪問的設置後,通過abc.com無法訪問服務器了,www.abc.com可以訪問

用 Nginx -t 檢測配置文件會提示warning:

  1. [warn]: conflicting server name “abc.com” on 0.0.0.0:80, 
    ignored  
  2. the configuration file /usr/local/webserver/Nginx/conf/
    Nginx.conf syntax is ok  
  3. configuration file /usr/local/webserver/Nginx/conf/Nginx.
    conf test is successful 

最後通過在listen 80 default;後再加server_name _;解決,形式如下:

  1. #禁止IP訪問  
  2. server  
  3. {  
  4. listen 80 default;  
  5. server_name _;  
  6. return 500;  

下面我們就向大家詳細的介紹有關Nginx配置的相關信息。

  1. #運行用戶   
  2. user nobody nobody;   
  3. #啓動進程   
  4. worker_processes 2;   
  5. #全局錯誤日誌及PID文檔   
  6. error_log logs/error.log notice;   
  7. pid logs/Nginx.pid;   
  8. #工作模式及連接數上限   
  9. events {   
  10. use epoll;   
  11. worker_connections 1024;   
  12. }   
  13. #設定http服務器,利用他的反向代理功能提供負載均衡支持   
  14. http {   
  15. #設定mime類型   
  16. include conf/mime.types;   
  17. default_type application/octet-stream;   
  18. #設定日誌格式   
  19. log_format main '$remote_addr - $remote_user [$time_local] '   
  20. '"$request" $status $bytes_sent '   
  21. '"$http_referer" "$http_user_agent" '   
  22. '"$gzip_ratio"';   
  23. log_format download '$remote_addr - $remote_user [$time_local] '   
  24. '"$request" $status $bytes_sent '   
  25. '"$http_referer" "$http_user_agent" '   
  26. '"$http_range" "$sent_http_content_range"';   
  27. #設定請求緩衝   
  28. client_header_buffer_size 1k;   
  29. large_client_header_buffers 4 4k;   
  30. #開啓gzip模塊   
  31. gzip on;   
  32. gzip_min_length 1100;   
  33. gzip_buffers 4 8k;   
  34. gzip_types text/plain;   
  35. output_buffers 1 32k;   
  36. postpone_output 1460;   
  37. #設定access log   
  38. access_log logs/access.log main;   
  39. client_header_timeout 3m;   
  40. client_body_timeout 3m;   
  41. send_timeout 3m;   
  42. sendfile on;   
  43. tcp_nopush on;   
  44. tcp_nodelay on;   
  45. keepalive_timeout 65;   
  46. #設定負載均衡的服務器列表   
  47. upstream mysvr {   
  48. #weigth參數表示權值,權值越高被分配到的機率越大   
  49. #本機上的Squid開啓3128端口   
  50. server 192.168.8.1:3128 weight=5;   
  51. server 192.168.8.2:80 weight=1;   
  52. server 192.168.8.3:80 weight=6;   
  53. }   
  54. #設定虛擬主機   
  55. server {   
  56. listen 80;   
  57. server_name 192.168.8.1   
  58. www.yejr.com   
  59. ;   
  60. charset gb2312;   
  61. #設定本虛擬主機的訪問日誌   
  62. access_log logs/www.yejr.com.access.log main;   
  63. #假如訪問 /img/*, /js/*, /css/* 資源,則直接取本地文檔,不通過squid   
  64. #假如這些文檔較多,不推薦這種方式,因爲通過squid的緩存效果更好   
  65. location ~ ^/(img|js|css)/ {   
  66. root /data3/Html;   
  67. expires 24h;   
  68. }   
  69. #對 "/" 啓用負載均衡   
  70. location / {   
  71. proxy_pass http://mysvr;   
  72. proxy_redirect off;   
  73. proxy_set_header Host $host;   
  74. proxy_set_header X-Real-IP $remote_addr;   
  75. proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;   
  76. client_max_body_size 10m;   
  77. client_body_buffer_size 128k;   
  78. proxy_connect_timeout 90;   
  79. proxy_send_timeout 90;   
  80. proxy_read_timeout 90;   
  81. proxy_buffer_size 4k;   
  82. proxy_buffers 4 32k;   
  83. proxy_busy_buffers_size 64k;   
  84. proxy_temp_file_write_size 64k;   
  85. }   
  86. #設定查看Nginx狀態的地址   
  87. location /NginxStatus {   
  88. stub_status on;   
  89. access_log on;   
  90. auth_basic "NginxStatus";   
  91. auth_basic_user_file conf/htpasswd;   
  92. }   
  93. }   
  94. }  

備註:conf/htpasswd 文檔的內容用 apache 提供的 htpasswd 工具來產生即可,內容大致如下:

3.) 查看 Nginx 運行狀態 輸入地址http://192.168.8.1/NginxStatus/ 。輸入驗證帳號密碼,即可看到類似如下內容:

  1. Active connections: 328   
  2. server accepts handled requests   
  3. 9309 8982 28890   
  4. Reading: 1 Writing: 3 Waiting: 324  

第一行表示現在活躍的連接數,第三行的第三個數字表示Nginx運行到

 

nginx配置文件正確與否的檢測方法。希望大家在以後的使用中有所收穫。

檢測nginx配置文件是否正確

  1. /usr/local/nginx/sbin/nginx -t -c nginx.conf  
  2. -c 配置文件路徑  
  3. -g Set global directives. (version >=0.7.4)  
  4. -t 檢測文件是否正確不執行  
  5. -v Print version.  
  6. -V Print nginx version, compiler version and configure 
    parameters. 

 

編譯時如果使用了–with-debug編譯,還可以使用error_log file [ debug_core| debug_http | debug_event …] 來獲得debug信息

通過信號對 Nginx配置文件 進行控制

Nginx配置文件 支持下表中的信號:

信號名 作用描述

 

  1. TERM, INT 快速關閉程序,中止當前正在處理的請求   
  2. QUIT 處理完當前請求後,關閉程序   
  3. HUP 重新加載配置,並開啓新的工作進程,關閉就的進程,此操作不會中斷請求   
  4. USR1 重新打開日誌文件,用於切換日誌,例如每天生成一個新的日誌文件   
  5. USR2 平滑升級可執行程序   
  6. WINCH 從容關閉工作進程  

有兩種方式來通過這些信號去控制 Nginx配置文件,第一是通過 logs 目錄下的 nginx.pid 查看當前運行的 Nginx 的進程 ID,通過 kill – XXX <pid> 來控制 Nginx,其中 XXX 就是上表中列出的信號名。如果您的系統中只有一個 Nginx 進程,那您也可以通過 killall 命令來完成,例如運行 killall – s HUP nginx 來讓 Nginx 重新加載配置。

配置:

 

  1. use [ kqueue | rtsig | epoll | /dev/poll | select | poll ];
    FreeBSD使用kqueue,Linux選epoll.  
  2. worker_connections number 每個worker的最大連接數  
  3. Maxclient = work_processes * worker_connections 

 

nginx的upstream目前支持4種方式的分配

1、輪詢(默認)

每個請求按時間順序逐一分配到不同的後端服務器,如果後端服務器down掉,能自動剔除。

2、weight

指定輪詢機率,weight和訪問比率成正比,用於後端服務器性能不均的情況。

2、ip_hash

每個請求按訪問ip的hash結果分配,這樣每個訪客固定訪問一個後端服務器,可以解決session的問題。

3、fair(第三方)

按後端服務器的響應時間來分配請求,響應時間短的優先分配。

4、url_hash(第三方)

按訪問url的hash結果來分配請求,使每個url定向到同一個後端服務器,後端服務器爲緩存時比較有效。

代理只需要在nginx配置文件中增加虛擬主機,然後加入

  1. \proxy_pass http://localhost:8000; 

 

負載均衡:只需要在http中增加

  1. upstream tgcluster {#定義負載均衡設備的Ip及設備狀態  
  2. ip_hash;  
  3. server 127.0.0.1:9090 down;  
  4. server 127.0.0.1:8080 weight=2;  
  5. server 127.0.0.1:6060;  
  6. server 127.0.0.1:7070 backup;  

在需要使用負載均衡的server中增加

  1. proxy_pass http://tgcluster/; 

每個設備的狀態設置爲:

1.down 表示單前的server暫時不參與負載
2.weight 默認爲1.weight越大,負載的權重就越大。
3.max_fails :允許請求失敗的次數默認爲1.當超過最大次數時,返回proxy_next_upstream 模塊定義的錯誤
4.fail_timeout:max_fails次失敗後,暫停的時間。
5.backup: 其它所有的非backup機器down或者忙的時候,請求backup機器。所以這臺機器壓力會最輕。

nginx配置文件支持同時設置多組的負載均衡,用來給不用的server來使用。

client_body_in_file_only 設置爲On 可以講client post過來的數據記錄到文件中用來做debug
client_body_temp_path 設置記錄文件的目錄 可以設置最多3層目錄

location 對URL進行匹配.可以進行重定向或者進行新的代理 負載均衡

FASTCGI配置:

請將以下內容保存爲fastcgi_params文件,保存於/usr/local/nginx/conf下(Ubuntu可保存於/etc/nginx下),他爲我們的FastCGI模塊設置了基本的環境變量:

  1. #fastcgi_params  
  2. fastcgi_param GATEWAY_INTERFACE CGI/1.1;  
  3. fastcgi_param SERVER_SOFTWARE nginx;  
  4. fastcgi_param QUERY_STRING $query_string;  
  5. fastcgi_param REQUEST_METHOD $request_method;  
  6. fastcgi_param CONTENT_TYPE $content_type;  
  7. fastcgi_param CONTENT_LENGTH $content_length;  
  8. fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;  
  9. fastcgi_param SCRIPT_NAME $fastcgi_script_name;  
  10. fastcgi_param REQUEST_URI $request_uri;  
  11. fastcgi_param DOCUMENT_URI $document_uri;  
  12. fastcgi_param DOCUMENT_ROOT $document_root;  
  13. fastcgi_param SERVER_PROTOCOL $server_protocol;  
  14. fastcgi_param REMOTE_ADDR $remote_addr;  
  15. fastcgi_param REMOTE_PORT $remote_port;  
  16. fastcgi_param SERVER_ADDR $server_addr;  
  17. fastcgi_param SERVER_PORT $server_port;  
  18. fastcgi_param SERVER_NAME $server_name;  
  19. # PHP only, required if PHP was built with 
    –enable-force-cgi-redirect 

fastcgi_param REDIRECT_STATUS 200;請特別注意加粗的一行,PHP-CGI特別需要此行信息來確定PHP文件的位置。

另外需要在PHP-CGI的配置文件(Ubuntu 上此配置文件位於/etc/php5/cgi/php.ini)中,打開cgi.fix_pathinfo選項:

cgi.fix_pathinfo=1;這樣php-cgi方能正常使用SCRIPT_FILENAME這個變量。

接下來在nginx的配置中針對php文件配置其利用FastCGI進程來執行:

 

  1. server {  
  2. index index.php;  
  3. root /usr/local/nginx/html;  
  4. location ~ .*.php$ {  
  5. include /usr/local/nginx/conf/fastcgi_params; 
    #請根據自己保存的路徑進行設置  
  6. fastcgi_index index.php;  
  7. fastcgi_pass 127.0.0.1:9000; 
    #請根據自己的FastCGI綁定的地址和端口進行配置  
  8. }  

 

通知Nginx重新載入配置:

kill -HUP `cat /usr/local/nginx/logs/nginx.pid`Ubuntu用戶可以使用init腳本:sudo /etc/init.d/nginx reload

然後啓動php-cgi -b 127.0.0.1:9000

如果出現No input file specified表示SCRIPT_FILENAME設置的有問題。使用lighttpd的 spawn-fcgi

 

  1. get http://www.lighttpd.net/download/lighttpd-1.4.18.tar.bz2 
    #獲取Lighttpd的源碼包  
  2. tar -xvjf lighttpd-1.4.18.tar.bz2  
  3. cd lighttpd-1.4.18  
  4. ./configure #編譯  
  5. make  
  6. cp src/spawn-fcgi /usr/local/bin/spawn-fcgi 
    #取出spawn-fcgi的程序 

以上就是對nginx配置文件如何檢測的相關介紹希望大家有所收穫。

 

1. 下載最新版的AWStats,基本就是Perl包,所以沒必要用apt-get,解壓縮到/usr/local/awstats下

wget http://prdownloads.sourceforge.net/awstats/awstats-6.95.tar.gz
tar -xzf awstats-6.95.tar.gz
mv awstats-6.95 /usr/local/awstats

2. 創建一個存放awstats分析數據的目錄

mkdir /var/lib/awstats
chown www-data /var/lib/awstats //這是爲了讓awstats頁面上能直接刷新最新數據

3. 自動配置awstats

cd /usr/local/awstats/tools
perl awstats_configure.pl

除了第一步因爲是Ngin服務器的關係,所以要選none,其他基本按照提示選默認值

4. 手工編輯Nginx配置文件

1) 修改LogFile路徑

LogFile = “/var/log/Nginx/access.log”

如果是壓縮格式的日誌,可以用LogFile = “zcat /var/log/Nginx/%YYYY-24%MM-24%DD-24.gz|"。這裏用zcat是因爲其使用管道輸出,對系統資源消耗比較小,千萬不要忘了最後的管道操作符!

假設原來/etc/Nginx/Nginx.conf中關於log部分是如此定義的:(要小心各個變量之間必須添加的空格,不能少,否則awstats就不認了)

log_format main ‘$remote_addr $remote_user [$time_local] “$request” $status ‘
‘$host $body_bytes_sent $gzip_ratio “$http_referer” ‘
‘”$http_user_agent” “$http_x_forwarded_for”‘;

很容易知道,對應awstats配置文件中,LogFormat應該設置爲
LogFormat= “%host %logname %time1 %methodurl %code %host_r %bytesd %gzipratio %refererquot %uaquot %otherquot”

最後一個選%otherquot是應爲$http_x_forwarded_for在AWstats 6.95中還不認識

3) 將AllowToUpdateStatsFromBrowser=1,便於瀏覽器中即時刷新數據

5. 更新Awstats的分析記錄,測試一下剛纔的配置

/usr/local/awstats/wwwroot/cgi-bin/awstats.pl -update -config=yousite.com

如果一切正常,應該看到類似以下的結果:

Create/Update database for config “/etc/awstats/awstats.yoursite.com.conf” by AWStats version 6.95 (build 1.943)
From data in log file “/var/log/Nginx/access.log”…
Phase 1 : First bypass old records, searching new record…
Searching new records from beginning of log file…
Phase 2 : Now process new records (Flush history on disk after 20000 hosts)…
Jumped lines in file: 0
Parsed lines in file: 1234
Found 0 dropped records,
Found 0 corrupted records,
Found 0 old records,
Found 1234 new qualified records.

6. 修改logrotate.d下的Nginx配置文件,在每天切割日誌前,更新awstats狀態

  1. /var/log/nginx/*.log {  
  2. daily  
  3. missingok  
  4. rotate 7  
  5. compress  
  6. delaycompress  
  7. notifempty  
  8. create 640 www-data www-data  
  9. dateext  
  10. sharedscripts  
  11. prerotate  
  12. /usr/local/awstats/wwwroot/cgi-bin/awstats.pl -update -config=yoursite.com  
  13. sleep 59  
  14. endscript  
  15. postrotate  
  16. if [ -f /var/run/nginx.pid ]; then  
  17. kill -USR1 `cat /var/run/nginx.pid`  
  18. fi  
  19. endscript  

7. 接下來是最關鍵的NGINX配置文件

 

  1. #AWStatus Perl CGI server  
  2. server {  
  3. listen 80;  
  4. server_name awstats.yoursite.com;  
  5. access_log /var/log/nginx/awstats.log main;  
  6. error_log /var/log/nginx/awstats_error.log; #這可以爲fail2ban留下記錄  
  7. root /usr/local/awstats/wwwroot;  
  8. auth_basic “Restricted”;  
  9. auth_basic_user_file /etc/nginx/awstatus.pass;  
  10. location = / {  
  11. rewrite ^ /awstats.pl?config=freshventure.info;  
  12. }  
  13. location ~ .*(\.cgi|\.pl?)$ {  
  14. gzip off; #gzip makes scripts feel slower since they have to complete before getting gzipped  
  15. root /usr/local/awstats/wwwroot/cgi-bin;  
  16. fastcgi_pass 127.0.0.1:8000;  
  17. fastcgi_index awstats.pl;  
  18. fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;  
  19. include fastcgi_params;  
  20. }  

 

好了,測試一下http://awstats.yoursite.com,和前文一樣,輸入密碼後,這次看到的應該就awstats的界面了

8. 如果需要配置靜態頁面,則可以在logrotate中替換掉上面的awstats.pl, 換成

/usr/local/awstats/tools/awstats_buildstaticpages.pl -update -config=yoursite.com -lang=cn -dir=/usr/local/awstats/wwwroot -awstatsprog=/usr/local/awstats/wwwroot/cgi-bin/awstats.pl。

如果需要更頻繁的更新訪問情況,則可以把這句命令加入到crontab中,例如crontab -e -uwww-data。

然後nginx配置文件相應調整爲顯示靜態網頁就可以了。

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