Nginx總結(二)——配置負載均衡和反向代理

nginx配置文件主要分爲六個區域:

  1. main(全局設置)
  2. events(nginx工作模式)
  3. http(http設置)
  4. sever(主機設置)
  5. location(URL匹配)
  6. upstream(負載均衡服務器設置)

有興趣的同學可以詳細去了解一下,這裏我們只用到了server,location,upstream區域。

server配置

#相當於在http模塊再添加一個server模塊
server {
	#監聽綁定80端口
    listen       80; 
	#下面這個是域名,多個域名用空格隔開
    server_name  www.php20.com php20.com;
	#本網站的根路徑
    root   /絕對路徑;
	#下面是默認首頁
    location / {
    	#配置默認頁面
        index  index.html;
        #配置代理服務器
        proxy_pass
    }
	#下面是針對本站所有.php文件進行處理的配置
    location / {
		#加載fastcgi  一種處理方式
        include fastcgi_params;
		#fastcgi的參數 指定文件路徑及參數,否則會有404或是file not find 提示
        fastcgi_param SCRIPT_FILENAME 
		#fastcgi的服務信息 ip:端口
        fastcgi_pass 127.0.0.1:9000;
		#fastcgi默認首頁
        fastcgi_index index.php;
    }
}

location配置

用戶可以通過location指令實現Nginx對動、靜態網頁的過濾處理。

  • location = /uri    =開頭表示精確匹配,只有完全匹配上才能生效。
  • location ^~ /uri   ^~ 開頭對URL路徑進行前綴匹配,並且在正則之前。
  • location ~ pattern  ~ 開頭表示區分大小寫的正則匹配。
  • location ~* pattern  ~* 開頭表示不區分大小寫的正則匹配。
  • location /uri     不帶任何修飾符,也表示前綴匹配,但是在正則匹配之後。
  • location /      通用匹配,任何未匹配到其它location的請求都會匹配到,相當於switch中的default。
location / {
	proxy_pass   http://tomcatserver;  
    # root   html;
    # index  index.html index.html;
}

upstream配置

在upstream參數中添加的應用服務器IP後添加指定參數即可實現負載均衡與分發策略。

upstream myServer {    
    server 127.0.0.1:8081;   
    server 127.0.0.1:8082;    
    server 127.0.0.1:8083;    
}

配置Nginx負載均衡和反向代理

第一步:啓動三個tomcat

在本地啓動三個tomcat,模擬三臺服務器,記得修改端口號,否則會端口衝突啓動不起來(一個tomcat涉及到三個端口,都需要修改,8080,8005,8009,只要這三個端口號和其他tomcat端口都不一樣即可)。我修改的三個tomcat訪問端口:8081,8082,8083。
在這裏插入圖片描述

第二步:創建頁面區分訪問的那個tomcat

在每個tomcat下,添加一個頁面Test.html,這三個頁面稍微可以不一樣點,用戶區分nginx會訪問不同的tomcat。

<!DOCTYPE html>
<html>
	<head>
		<title>index</title>
		<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
	</head>
	<body>
		<h1>Tomcat——8081</h1>
	</body>
</html>

在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述

第三步:配置nginx

配置nginx的nginx.conf文件

upstream tomcatserver{    
    server 127.0.0.1:8081;   
    server 127.0.0.1:8082;    
    server 127.0.0.1:8083;    
}
server {
        listen       90;
        server_name  localhost;

        location / {
        	# 配置代理服務器,從上邊三個tomcat中選擇一個進行訪問
			proxy_pass   http://tomcatserver;  
        }
}

第四步:啓動nginx

不斷訪問 http://localhost:90/Test.html,就可以看到以下三個頁面,依次出現
在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述

Nginx的負載分發策略

Nginx 的 upstream目前支持的分配算法:

  1. 輪詢 ——1:1 輪流處理請求(默認)
    每個請求按時間順序逐一分配到不同的應用服務器,如果應用服務器down掉,自動剔除,剩下的繼續輪詢。
  2. 權重 ——you can you up
    通過配置權重,指定輪詢機率,權重和訪問比率成正比,用於應用服務器性能不均的情況。
  3. ip_哈希算法
    每個請求按訪問ip的hash結果分配,這樣每個訪客固定訪問一個應用服務器,可以解決session共享的問題。

nginx其他配置

upstream myServer {    
	server 127.0.0.1:8081 down;   
    server 127.0.0.1:8082 weight=2;    
    server 127.0.0.1:8083;    
    server 127.0.0.1:8084 backup;   
}
  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 運行的用戶和用戶組,默認由 nobody 賬號運行, windows 下面可以註釋掉。 
#user  nobody; 
 
#nginx進程數,建議設置爲等於CPU總核心數。可以和worker_cpu_affinity配合
worker_processes  1; 
 
#全局錯誤日誌定義類型,[ debug | info | notice | warn | error | crit ]
#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;
 
#進程文件,window下可以註釋掉
#pid        logs/nginx.pid;
 
# 一個nginx進程打開的最多文件描述符(句柄)數目,理論值應該是最多打開文件數(系統的值ulimit -n)與nginx進程數相除,
# 但是nginx分配請求並不均勻,所以建議與ulimit -n的值保持一致。
worker_rlimit_nofile 65535;
 
#工作模式與連接數上限
events {
    # 參考事件模型,use [ kqueue | rtsig | epoll | /dev/poll | select | poll ]; 
    # epoll模型是Linux 2.6以上版本內核中的高性能網絡I/O模型,如果跑在FreeBSD上面,就用kqueue模型。
   #use epoll;
   #connections 20000;  # 每個進程允許的最多連接數
   # 單個進程最大連接數(最大連接數=連接數*進程數)該值受系統進程最大打開文件數限制,需要使用命令ulimit -n 查看當前設置
   worker_connections 65535;
}
 
#設定http服務器
http {
    #文件擴展名與文件類型映射表
    #include 是個主模塊指令,可以將配置文件拆分並引用,可以減少主配置文件的複雜度
    #include       mime.types;
    #默認文件類型
    #default_type  application/octet-stream;
    #charset utf-8; #默認編碼
 
    #定義虛擬主機日誌的格式
    #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函數來輸出文件,對於普通應用設爲 on,如果用來進行下載等應用磁盤IO重負載應用,可設置爲off,以平衡磁盤與網絡I/O處理速度,降低系統的負載。注意:如果圖片顯示不正常把這個改成off。
    sendfile        on;
    #autoindex on; #開啓目錄列表訪問,合適下載服務器,默認關閉。
 
    #防止網絡阻塞
    #tcp_nopush     on;
 
    #長連接超時時間,單位是秒,默認爲0
    keepalive_timeout  65;
 
    # gzip壓縮功能設置
    gzip on; #開啓gzip壓縮輸出
    gzip_min_length 1k; #最小壓縮文件大小
    gzip_buffers    4 16k; #壓縮緩衝區
    gzip_http_version 1.0; #壓縮版本(默認1.1,前端如果是squid2.5請使用1.0)
    gzip_comp_level 6; #壓縮等級
    #壓縮類型,默認就已經包含text/html,所以下面就不用再寫了,寫上去也不會有問題,但是會有一個warn。
    gzip_types text/plain text/css text/javascript application/json application/javascript application/x-javascript application/xml;
    gzip_vary on; #//和http頭有關係,加個vary頭,給代理服務器用的,有的瀏覽器支持壓縮,有的不支持,所以避免浪費不支持的也壓縮,所以根據客戶端的HTTP頭來判斷,是否需要壓縮
    #limit_zone crawler $binary_remote_addr 10m; #開啓限制IP連接數的時候需要使用
 
    # http_proxy服務全局設置
    client_max_body_size   10m;
    client_body_buffer_size   128k;
    proxy_connect_timeout   75;
    proxy_send_timeout   75;
    proxy_read_timeout   75;
    proxy_buffer_size   4k;
    proxy_buffers   4 32k;
    proxy_busy_buffers_size   64k;
    proxy_temp_file_write_size  64k;
    # proxy_temp_path   /usr/local/nginx/proxy_temp 1 2;
 
   # 設定負載均衡後臺服務器列表 
    #upstream  backend.com  { 
        #ip_hash; # 指定支持的調度算法
        # upstream 的負載均衡,weight 是權重,可以根據機器配置定義權重。weigth 參數表示權值,權值越高被分配到的機率越大。
        #server   192.168.10.100:8080 max_fails=2 fail_timeout=30s ;  
        #server   192.168.10.101:8080 max_fails=2 fail_timeout=30s ;  
    #}
 
    #虛擬主機的配置
    server {
        #監聽端口
        listen       80;
        #域名可以有多個,用空格隔開
        server_name  localhost fontend.com;
        # Server Side Include,通常稱爲服務器端嵌入
        #ssi on;
        #默認編碼
        charset utf-8;
        #定義本虛擬主機的訪問日誌
        #access_log  logs/host.access.log  main;
        
        # 因爲所有的地址都以 / 開頭,所以這條規則將匹配到所有請求
        location /usr/share/nginx/ {
            root   html;
            index  index.html index.htm;
        }
        
        #error_page  404              /404.html;
 
        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
 
       # 圖片緩存時間設置
       location ~ .*.(gif|jpg|jpeg|png|bmp|swf)$ {
          expires 10d;
       }
 
       # JS和CSS緩存時間設置
       location ~ .*.(js|css)?$ {
          expires 1h;
       }
 
        #代理配置
        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #location /proxy/ {
        #    proxy_pass   http://127.0.0.1;
        #}
 
        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}
 
        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    }
 
    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;
 
    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}
 
    # HTTPS server
    #
    #server {
    #    listen       443 ssl;
    #    server_name  localhost;
 
    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;
 
    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;
 
    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;
 
    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章