nginx-7+4層負載均衡

7層負載均衡

https://docs.nginx.com/nginx/admin-guide/load-balancer/http-load-balancer/ --》詳細版本

http://nginx.org/en/docs/http/load_balancing.html --》精簡版本

算法: method --》方法
backend --》後端
nginx做負載均衡的方法有哪些?
1.Round Robin --》RR 輪詢 、輪叫 --》默認的方法

server weights   服務器的權重
server backend1.example.com      weight=5;  --》加權輪詢---》weight值越大,負載均衡器在分配任何的時候會多分任務給它  默認值爲1

upstream myapp1 {
server srv1.example.com;
server srv2.example.com;
server srv3.example.com;
server backend1.example.com weight=5;
}

2.Least Connections 最小連接數
upstream backend {
least_conn;
server backend1.example.com;
server backend2.example.com;
}

3.ip-hash

是基於客戶機的ip地址來轉發到後端真實服務器的
相同的ip地址的所有的請求都會發送到同一臺的真實服務器上
購物:---》登陸的信息,購物車裏的信息----》session會話信息 

upstream myapp1 {
ip_hash;
server srv1.example.com;
server srv2.example.com;
server srv3.example.com;
}
4. generic hash 可以根據uri來做調度

upstream backend {
hash $request_uri consistent;
server backend1.example.com;
server backend2.example.com;
}

cookie和session的區別?

cookie和session都是用來保存信息的方法和技術。
cookie和session都理解爲一個容器,裏面用來裝一些用戶的信息

cookie是存放在客戶端的瀏覽器裏
session是存儲在服務器裏的

HTTP是一種無狀態的協議,爲了分辨鏈接是誰發起的,就需要我們自己去解決這個問題。

無狀態 --》如何理解?
區別不了,你是新的連接還是舊的連接,每次連接都是全新的對待,每次連接沒有區別

HTTP是一種無狀態的協議,爲了分辨鏈接是誰發起的,就需要我們自己去解決這個問題。不然有些情況下即使是同一個網站我們每打開一個頁面也都要登錄一下。而Session和Cookie就是爲解決這個問題而提出來的兩個機制。

https://www.cnblogs.com/wswang/p/6062461.html

Hash,一般翻譯做散列、雜湊,或音譯爲哈希,是把任意長度的輸入(又叫做預映射pre-image)通過散列算法變換成固定長度的輸出,該輸出就是散列值.

lihu
lidahu
tanzikun
tanxiaokun

#將任意長度的名字取第1個字母和最後一個字母,拼接成一個字符串,輸出
def sc_fun(name):
hash_msg = name[0] + name[-1]
reture hash_msg

[root@localhost ~]# cat sc.py
def sc_fun(name):
hash_msg = name[0] + name[-1]
return hash_msg

sc_name = input(“請輸入你的名字的漢語拼音:”)
print(f"你的名字的hash值是{sc_fun(sc_name)}")
[root@localhost ~]#

========
負載均衡器:自己不需要提供web服務,它只是將web請求轉發到後端的real server

1.定義負載均衡器
定義在http語句塊裏
#定義一個負載均衡器名字叫sanchuang 調度器
#upstream 上游
upstream sanchuang {
server 192.168.0.19;
server 192.168.0.20;
#server 192.168.0.25;
#server 192.168.0.200;
}

2.將訪問請求轉發到負載均衡器

server {
    listen       80;
    server_name  www.sc.com;
    location / {
        proxy_pass http://sanchuang;
        #health_check;
    }

休息20分鐘
15:28 ~ 15:48
問題:
後端的real server知道前端真正的用戶的ip地址?
答案:不知道,因爲LB在轉發數據的時候,將ip包裏的源ip修改爲自己的ip地址,目的ip地址也修改爲選中的一個後端的real
server 的ip地址

 客戶機是不知道LB後端有多少臺real server的,也不知道real server的ip地址
 暴露在外面的只是LB的ip地址

客戶端---》LB-->real server   real server -->LB--->客戶機



後端的real server不知道前端真正訪問的ip地址,只是知道負載均衡的ip地址,如何讓後端的real server知道前端真正的用戶的ip地址?

[root@nginx-server-1 html]# yum install tcpdump -y

[root@nginx-server-1 html]# tcpdump -i ens33 tcp and port 80 -nn

-i ens33 抓ens33網卡的數據 interface
tcp 協議
port 80 端口號是80
dst port 80 目的端口
src port 80 源端口
and 多個條件組合

-nn 以數字的形式顯示

log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                 '$status $body_bytes_sent "$http_referer" '
                  '"$http_user_agent" "$http_x_forwarded_for"';
nginx的日誌得到的內容都是從nginx這個進程裏獲取的,上面的這些都是nginx內部的變量

這些變量的初始值都爲空,然後會去讀取http的請求報文和響應報文然後從新賦值給這些變量

問題:
後端的real server不知道前端真正訪問的ip地址,只是知道負載均衡的ip地址,如何讓後端的real server知道前端真正的用戶的ip地址?

1.在反向代理服務器(負載均衡服務器上)對http協議的頭部信息進行修改

 location / {
        proxy_pass http://sanchuang;
        proxy_set_header   X-Real-IP        $remote_addr;  將nginx內部的remote_addr這個變量的值,賦值給X-Real-IP這個變量,X-Real-IP這個變量會在http協議的請求報文裏添加一個X-Real-IP的字段,後端的real server 服務器上的nginx就可以讀取這個字段的值
        X-Real-IP  這個變量名可以自己定義,隨便取名,後面引用的時候,不區分大小寫



        #proxy_set_header 指令的作用就是告訴nginx去修改http協議的頭部信息,增加一個字段
		proxy_set_header   Host             $host;    #是http協議裏的host關鍵字 對應Host這個變量

    }

前面的修改了http頭部信息的字段,在後面的nginx服務器裏獲取的時候,需要在變量名前面加HTTP

  2.在後端real server的nginx上修改日誌的格式,添加$HTTP_X_REAL_IP 字段和$HTTP_Host

log_format  main  '$HTTP_X_REAL_IP - $remote_addr - $remote_user [$time_local] "$request" '
                  '$status $body_bytes_sent "$http_referer" '
                  '"$http_user_agent" "$http_x_forwarded_for"  $HTTP_Host';

===========

休息20分鐘
10:46 ~ 11:06

反向代理和正向代理

proxy 代理
Reverse 相反的
Reverse Proxy --》反向代理

URL:統一資源定位符
https://www.qq.com:80/sanchuang/feng.html
協議+域名(ip)+端口號+服務器裏的文件的路徑

URI:統一資源標識符
協議+域名(ip)+端口號+服務器裏的文件的路徑+參數
https://www.qq.com:80/sanchuang?name=feng&age=36&sex=male
服務器裏的文件的路徑

location = / {
[ configuration A ]
}

location / {
[ configuration B ]
}

location /documents/ {
[ configuration C ]
}

location ^~ /images/ {
[ configuration D ]
}

location ~* .(gif|jpg|jpeg)$ {
[ configuration E ]
}

https://www.baidu.com/s?ie=utf-8&f=8&rsv_bp=1&rsv_idx=1&tn=baidu&wd=%E5%86%AF%E5%BE%B7%E5%8B%87&fenlei=256&rsv_pq=8cca9713000d0ade&rsv_t=ceff6y982wavU8

健康檢查 Health checks
max_fails 失敗的最多的次數
fail_timeout 失敗超時的時間

upstream backend {
server backend1.example.com;
server backend2.example.com max_fails=3 fail_timeout=30s;
在30秒以內達到失敗的次數到3次,就標識這臺server 爲down機狀態。
}

Passive Health Checks 被動的健康檢查: 當client發請求給LB,然後LB再去轉發請求給後端的real server ,這個時候如果後端的服務器出現問題,LB就發現了。被客戶機逼着去檢查後端的real server

對於每個上游服務器,使用塊中server指令的參數定義了標記上游服務器不可用的條件upstream:

fail_timeout –設置必須多次嘗試失敗才能將服務器標記爲不可用的時間,以及將服務器標記爲不可用的時間(默認爲10秒)。
max_fails –設置在fail_timeout服務器標記爲不可用的時間內必須發生的失敗嘗試次數(默認爲1次嘗試)。
backup 備份:當其他的服務器都不提供服務的時候,再啓用這臺服務器提供服務 --》備胎
slow_start 慢啓動
down 將上游的服務器標識爲不可用,不會再發送任何的請求給這臺服務器

upstream backend {
server backend1.example.com slow_start=30s; 晚30秒給上游的服務器轉發請求
server backend2.example.com;
server 192.0.0.1 backup;
}

Active Health Checks 主動的健康檢查,LB每隔一段時間就去檢查下後端的real server的狀態,不管是否有client發請求過來,都會去檢查。

by default, every five seconds NGINX Plus sends a request for “/” to each server in the backend group. If any communication error or timeout occurs (the server responds with a status code outside the range from 200 through 399) the health check fails. The server is marked as unhealthy, and NGINX Plus does not send client requests to it until it once again passes a health check.
NGINX 的健康檢測插件會每隔5秒鐘去訪問上游的服務器的網頁根目錄,如果返回的狀態碼不是200到399之間的,這個插件就會認爲上游的服務器掛了
到底是如何去檢查的,使用curl命令去訪問後端的服務器

server {
location / {
proxy_pass http://backend;
health_check port=8080; 指定檢測的端口號
}
}

location / {
proxy_pass http://backend;
health_check interval=10 fails=3 passes=2; 每隔10秒去檢查一次後端的real server, 失敗的次數到達3次的時候,就標識這臺上遊服務器不可用,如果連續2次又可用訪問了,就標識這臺上遊的服務器爲up(可用)
主動檢查:默認的失敗次數是1次,默認的時間間隔是5秒,默認只要能成功訪問一次就認爲服務器up 了

}

是負載均衡器去檢查後端的real server是否能正常,如果不正常,如果後端的real server宕機了,負載均衡器就不會再把請求轉發給這個宕機的real server

宕機: 死機 down 某個服務掛了,跪了

200
404
401
500
501
502
502 Bad Gateway --》負載均衡器後面的real server 全部down 了

休息20分鐘
15:58 ~ 16:18

[root@LB conf]# nginx -t
nginx: [emerg] unknown directive “health_check” in /usr/local/nginx9/conf/nginx.conf:56
nginx: configuration file /usr/local/nginx9/conf/nginx.conf test failed
[root@LB conf]#
NGINX Plus nginx的插件提供了 health_check的功能
安裝插件 NGINX Plus
https://docs.nginx.com/nginx/admin-guide/installing-nginx/installing-nginx-plus/#install_rhel_centos

軟件 —》購買
服務 --》購買

======================

nginx的4層負載均衡的配置

https://docs.nginx.com/nginx/admin-guide/load-balancer/tcp-udp-load-balancer/

[root@LB-4-layer conf]# cat nginx.conf|egrep -v “#”|egrep -v “^$”

worker_processes 2;
error_log logs/error.log info;
pid logs/nginx.pid;
events {
worker_connections 1024;
}
stream {
upstream sanchuang {
server 192.168.0.19:80;
server 192.168.0.20:80;
}
upstream dns_servers {
server 192.168.0.19:53;
server 192.168.0.20:53;
}
server {
listen 8080;
proxy_pass sanchuang;
}
server {
listen 53 udp;
proxy_pass dns_servers;
}
}
http {
include mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - remoteuser[remote_user [time_local] “KaTeX parse error: Double superscript at position 34: … '̲status bodybytessent"body_bytes_sent "http_referer” ’
‘“httpuseragent""http_user_agent" "http_x_forwarded_for”’;
access_log logs/access.log main;
sendfile on;
tcp_nopush on;
keepalive_timeout 65;
gzip on;
}

#注意下http語句塊裏沒有server語句塊了,server語句塊全部放到stream語句塊裏了 --》需要驗證

[root@LB-4-layer conf]#

[root@LB-4-layer conf]# netstat -naupltu
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 895/sshd
tcp 0 0 0.0.0.0:8080 0.0.0.0:* LISTEN 18760/nginx: master
tcp 0 36 192.168.0.74:22 192.168.0.15:56144 ESTABLISHED 1695/sshd: root [pr
tcp6 0 0 :::22 ::😗 LISTEN 895/sshd
udp 0 0 0.0.0.0:53 0.0.0.0:* 18760/nginx: master
udp 0 0 192.168.0.74:68 0.0.0.0:* 883/NetworkManager
[root@LB-4-layer conf]#

[root@LB-4-layer conf]# service firewalld stop
Redirecting to /bin/systemctl stop firewalld.service
[root@LB-4-layer conf]# getenforce
Enforcing
[root@LB-4-layer conf]# setenforce 0
[root@LB-4-layer conf]#
[root@LB-4-layer conf]#

查看負載均衡的記錄
查看
[root@LB-4-layer logs]# pwd
/usr/local/nginx9/logs
[root@LB-4-layer logs]#

[root@LB-4-layer logs]# tail -f error.log
020/05/08 17:36:04 [info] 18888#18888: *253 client 192.168.0.63:52460 connected to 0.0.0.0:8080
2020/05/08 17:36:04 [info] 18888#18888: *253 proxy 192.168.0.74:35696 connected to 192.168.0.20:80
2020/05/08 17:36:07 [info] 18888#18888: *249 client disconnected, bytes from/to client:0/0, bytes from/to upstream:0/0
2020/05/08 17:36:13 [info] 18888#18888: *255 client 192.168.0.33:52161 connected to 0.0.0.0:8080
2020/05/08 17:36:13 [info] 18888#18888: *255 proxy 192.168.0.74:36234 connected to 192.168.0.19:80
2020/05/08 17:36:13 [info] 18888#18888: *257 client 192.168.0.33:52162 connected to 0.0.0.0:8080
2020/05/08 17:36:13 [info] 18888#18888: *257 proxy 192.168.0.74:35700 connected to 192.168.0.20:80

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