Nginx負載均衡是一個很神奇的技術,很多人都不能很好的掌握這個技術,今天在這裏我們向大家詳細的介紹下有關Nginx負載均衡的問題。今天小試了一下Nginx負載均衡,真是爽啊!Nginx是什麼?
Nginx (”engine x”) 是一個高性能的 HTTP 和 反向代理 服務器,也是一個 IMAP/POP3/SMTP 代理服務器。 Nginx 是由 Igor Sysoev 爲俄羅斯訪問量第二的 Rambler.ru 站點開發的,它已經在該站點運行超過兩年半了。Igor 將源代碼以類BSD許可證的形式發佈。儘管還是測試版,但是,Nginx 已經因爲它的穩定性、豐富的功能集、示例配置文件和低系統資源的消耗而聞名了。
首先是配置十分的簡單,而且功能非常強大。真是相見恨晚。先來看看配置文件怎麼寫吧
- worker_processes 1;
- events {
- worker_connections 1024;
- }
- http{
- upstream myproject {
- #這裏指定多個源服務器,ip:端口,80端口的話可寫可不寫
- server 192.168.43.158:80;
- server 192.168.41.167;
- }
- server {
- listen 8080;
- location / {
- proxy_pass http://myproject;
- }
- }
- }
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的設置裏面添加這一行:
- listen 80 default;
後面的default參數表示這個是默認虛擬主機。
Nginx 禁止IP訪問這個設置非常有用。
比如別人通過ip或者未知域名訪問你的網站的時候,你希望禁止顯示任何有效內容,可以給他返回500.目前國內很多機房都要求網站主關閉空主機頭,防止未備案的域名指向過來造成麻煩。就可以這樣設置:
- server {
- listen 80 default;
- return 500;
- }
也可以把這些流量收集起來,導入到自己的網站,只要做以下跳轉設置就可以:
- server {
- listen 80 default;
- rewrite ^(.*) http://www.mydomain.com permanent;
- }
按照如上設置後,確實不能通過IP訪問服務器了,但是在應該用中出現當server_name後跟多個域名時,其中一個域名怎麼都無法訪問:
設置如下:
- server
- {
- listen 80;
- server_name www.abc.com abc.com
沒更改之前,通過server_name 中的www.abc.com abc.com均可訪問服務器,加入Nginx 禁止IP訪問的設置後,通過abc.com無法訪問服務器了,www.abc.com可以訪問
用 Nginx -t 檢測配置文件會提示warning:
- [warn]: conflicting server name “abc.com” on 0.0.0.0:80,
ignored- the configuration file /usr/local/webserver/Nginx/conf/
Nginx.conf syntax is ok- configuration file /usr/local/webserver/Nginx/conf/Nginx.
conf test is successful
最後通過在listen 80 default;後再加server_name _;解決,形式如下:
- #禁止IP訪問
- server
- {
- listen 80 default;
- server_name _;
- return 500;
- }
下面我們就向大家詳細的介紹有關Nginx配置的相關信息。
- #運行用戶
- user nobody nobody;
- #啓動進程
- worker_processes 2;
- #全局錯誤日誌及PID文檔
- error_log logs/error.log notice;
- pid logs/Nginx.pid;
- #工作模式及連接數上限
- events {
- use epoll;
- worker_connections 1024;
- }
- #設定http服務器,利用他的反向代理功能提供負載均衡支持
- http {
- #設定mime類型
- include conf/mime.types;
- default_type application/octet-stream;
- #設定日誌格式
- log_format main '$remote_addr - $remote_user [$time_local] '
- '"$request" $status $bytes_sent '
- '"$http_referer" "$http_user_agent" '
- '"$gzip_ratio"';
- log_format download '$remote_addr - $remote_user [$time_local] '
- '"$request" $status $bytes_sent '
- '"$http_referer" "$http_user_agent" '
- '"$http_range" "$sent_http_content_range"';
- #設定請求緩衝
- client_header_buffer_size 1k;
- large_client_header_buffers 4 4k;
- #開啓gzip模塊
- gzip on;
- gzip_min_length 1100;
- gzip_buffers 4 8k;
- gzip_types text/plain;
- output_buffers 1 32k;
- postpone_output 1460;
- #設定access log
- access_log logs/access.log main;
- client_header_timeout 3m;
- client_body_timeout 3m;
- send_timeout 3m;
- sendfile on;
- tcp_nopush on;
- tcp_nodelay on;
- keepalive_timeout 65;
- #設定負載均衡的服務器列表
- upstream mysvr {
- #weigth參數表示權值,權值越高被分配到的機率越大
- #本機上的Squid開啓3128端口
- server 192.168.8.1:3128 weight=5;
- server 192.168.8.2:80 weight=1;
- server 192.168.8.3:80 weight=6;
- }
- #設定虛擬主機
- server {
- listen 80;
- server_name 192.168.8.1
- www.yejr.com
- ;
- charset gb2312;
- #設定本虛擬主機的訪問日誌
- access_log logs/www.yejr.com.access.log main;
- #假如訪問 /img/*, /js/*, /css/* 資源,則直接取本地文檔,不通過squid
- #假如這些文檔較多,不推薦這種方式,因爲通過squid的緩存效果更好
- location ~ ^/(img|js|css)/ {
- root /data3/Html;
- expires 24h;
- }
- #對 "/" 啓用負載均衡
- location / {
- proxy_pass http://mysvr;
- proxy_redirect off;
- proxy_set_header Host $host;
- proxy_set_header X-Real-IP $remote_addr;
- proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
- client_max_body_size 10m;
- client_body_buffer_size 128k;
- proxy_connect_timeout 90;
- proxy_send_timeout 90;
- proxy_read_timeout 90;
- proxy_buffer_size 4k;
- proxy_buffers 4 32k;
- proxy_busy_buffers_size 64k;
- proxy_temp_file_write_size 64k;
- }
- #設定查看Nginx狀態的地址
- location /NginxStatus {
- stub_status on;
- access_log on;
- auth_basic "NginxStatus";
- auth_basic_user_file conf/htpasswd;
- }
- }
- }
備註:conf/htpasswd 文檔的內容用 apache 提供的 htpasswd 工具來產生即可,內容大致如下:
3.) 查看 Nginx 運行狀態 輸入地址http://192.168.8.1/NginxStatus/ 。輸入驗證帳號密碼,即可看到類似如下內容:
- Active connections: 328
- server accepts handled requests
- 9309 8982 28890
- Reading: 1 Writing: 3 Waiting: 324
第一行表示現在活躍的連接數,第三行的第三個數字表示Nginx運行到
關nginx配置文件正確與否的檢測方法。希望大家在以後的使用中有所收穫。
檢測nginx配置文件是否正確
- /usr/local/nginx/sbin/nginx -t -c nginx.conf
- -c 配置文件路徑
- -g Set global directives. (version >=0.7.4)
- -t 檢測文件是否正確不執行
- -v Print version.
- -V Print nginx version, compiler version and configure
parameters.
編譯時如果使用了–with-debug編譯,還可以使用error_log file [ debug_core| debug_http | debug_event …] 來獲得debug信息
通過信號對 Nginx配置文件 進行控制
Nginx配置文件 支持下表中的信號:
信號名 作用描述
- TERM, INT 快速關閉程序,中止當前正在處理的請求
- QUIT 處理完當前請求後,關閉程序
- HUP 重新加載配置,並開啓新的工作進程,關閉就的進程,此操作不會中斷請求
- USR1 重新打開日誌文件,用於切換日誌,例如每天生成一個新的日誌文件
- USR2 平滑升級可執行程序
- WINCH 從容關閉工作進程
有兩種方式來通過這些信號去控制 Nginx配置文件,第一是通過 logs 目錄下的 nginx.pid 查看當前運行的 Nginx 的進程 ID,通過 kill – XXX <pid> 來控制 Nginx,其中 XXX 就是上表中列出的信號名。如果您的系統中只有一個 Nginx 進程,那您也可以通過 killall 命令來完成,例如運行 killall – s HUP nginx 來讓 Nginx 重新加載配置。
配置:
- use [ kqueue | rtsig | epoll | /dev/poll | select | poll ];
FreeBSD使用kqueue,Linux選epoll.- worker_connections number 每個worker的最大連接數
- 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配置文件中增加虛擬主機,然後加入
- \proxy_pass http://localhost:8000;
負載均衡:只需要在http中增加
- upstream tgcluster {#定義負載均衡設備的Ip及設備狀態
- ip_hash;
- server 127.0.0.1:9090 down;
- server 127.0.0.1:8080 weight=2;
- server 127.0.0.1:6060;
- server 127.0.0.1:7070 backup;
- }
在需要使用負載均衡的server中增加
- 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模塊設置了基本的環境變量:
- #fastcgi_params
- 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;請特別注意加粗的一行,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進程來執行:
- server {
- index index.php;
- root /usr/local/nginx/html;
- location ~ .*.php$ {
- include /usr/local/nginx/conf/fastcgi_params;
#請根據自己保存的路徑進行設置- fastcgi_index index.php;
- fastcgi_pass 127.0.0.1:9000;
#請根據自己的FastCGI綁定的地址和端口進行配置- }
- }
通知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
- get http://www.lighttpd.net/download/lighttpd-1.4.18.tar.bz2
#獲取Lighttpd的源碼包- tar -xvjf lighttpd-1.4.18.tar.bz2
- cd lighttpd-1.4.18
- ./configure #編譯
- make
- 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狀態
- /var/log/ nginx /*.log {
- daily
- missingok
- rotate 7
- compress
- delaycompress
- notifempty
- create 640 www-data www-data
- dateext
- sharedscripts
- prerotate
- /usr/local/awstats/wwwroot/cgi-bin/awstats.pl -update -config=yoursite.com
- sleep 59
- endscript
- postrotate
- if [ -f /var/run/nginx.pid ]; then
- kill -USR1 `cat /var/run/nginx.pid`
- fi
- endscript
- }
7. 接下來是最關鍵的NGINX配置文件
- #AWStatus Perl CGI server
- server {
- listen 80;
- server_name awstats.yoursite.com;
- access_log /var/log/nginx/awstats.log main;
- error_log /var/log/nginx/awstats_error.log; #這可以爲fail2ban留下記錄
- root /usr/local/awstats/wwwroot;
- auth_basic “Restricted”;
- auth_basic_user_file /etc/nginx/awstatus.pass;
- location = / {
- rewrite ^ /awstats.pl?config=freshventure.info;
- }
- location ~ .*(\.cgi|\.pl?)$ {
- gzip off; #gzip makes scripts feel slower since they have to complete before getting gzipped
- root /usr/local/awstats/wwwroot/cgi-bin;
- fastcgi_pass 127.0.0.1:8000;
- fastcgi_index awstats.pl;
- fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
- include fastcgi_params;
- }
- }
好了,測試一下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配置文件相應調整爲顯示靜態網頁就可以了。