1. 程式人生 > >Nginx的配置3

Nginx的配置3

ces allow nbsp nac host 源地址 上下 ror 不可用

ngx_http_upstream_module模塊 #分流
The ngx_http_upstream_module module is used to define groups of servers that can be referenced by the proxy_pass, fastcgi_pass, uwsgi_pass, scgi_pass, and memcached_pass directives.

ngx_http_upstream_module模塊
The ngx_http_upstream_module module is used to define groups of servers that can be referenced by the proxy_pass, fastcgi_pass, uwsgi_pass, scgi_pass, and memcached_pass directives.

1、upstream name { … }
定義後端服務器組,會引入一個新的上下文;Context: http

upstream httpdsrvs {
server …
server…

}

2、server address [parameters];
在upstream上下文中server成員,以及相關的參數;Context: upstream

address的表示格式:
unix:/PATH/TO/SOME_SOCK_FILE
IP[:PORT]
HOSTNAME[:PORT]

parameters:
weight=number
權重,默認為1;
max_fails=number
失敗嘗試最大次數;超出此處指定的次數時,server將被標記為不可用;
fail_timeout=time
設置將服務器標記為不可用狀態的超時時長;
max_conns
當前的服務器的最大並發連接數;
backup
將服務器標記為“備用”,即所有服務器均不可用時此服務器才啟用;
down
標記為“不可用”;

3、least_conn;
最少連接調度算法,當server擁有不同的權重時其為wlc;

4、 ip_hash;
源地址hash調度方法;

5、hash key [consistent];
基於指定的key的hash表來實現對請求的調度,此處的key可以直接文本、變量或二者的組合;

作用:將請求分類,同一類請求將發往同一個upstream server;

If the consistent parameter is specified the ketama consistent hashing method will be used instead.

示例:
hash $request_uri consistent;
hash $remote_addr;

6、keepalive connections;
為每個worker進程保留的空閑的長連接數量;

nginx的其它的二次發行版:
tengine
OpenResty

ngx_stream_core_module模塊
模擬反代基於tcp或udp的服務連接,即工作於傳輸層的反代或調度器;

1、stream { … }
定義stream相關的服務;Context:main

stream {
upstream sshsrvs {
server 192.168.22.2:22;
server 192.168.22.3:22;
least_conn;
}

server {
listen 10.1.0.6:22022;
proxy_pass sshsrvs;
}
}

2、listen
listen address:port [ssl] [udp] [proxy_protocol] [backlog=number] [bind] [ipv6only=on|off] [reuseport] [so_keepalive=on|off|[keepidle]:[keepintvl]:[keepcnt]];

博客作業:以上所有內容;

思考:
(1) 動態資源存儲一組服務器、圖片資源存在一組服務器、靜態的文本類資源存儲在一組服務器;如何分別調度?
(2) 動態資源基於fastcgi或http協議(ap)?
lnamp

memcached:

memcached is a high-performance, distributed memory object caching system, generic in nature, but intended for use in speeding up dynamic web applications by alleviating database load.

緩存服務器:
緩存:cache,無持久存儲功能;
bypass緩存
k/v cache,僅支持存儲流式化數據;

LiveJournal旗下的Danga Interactive研發,

特性:
k/v cache:僅可序列化數據;存儲項:k/v;
智能性一半依賴於客戶端(調用memcached的API開發程序),一半依賴於服務端;
分布式緩存:互不通信的分布式集群;
分布式系統請求路由方法:取模法,一致性哈希算法;
算法復雜度:O(1)
清理過期緩存項:
緩存耗盡:LRU
緩存項過期:惰性清理機制

安裝配置:
由CentOS 7 base倉庫直接提供:
監聽的端口:
11211/tcp, 11211/udp

主程序:/usr/bin/memcached
配置文件:/etc/sysconfig/memcached
Unit File:memcached.service

協議格式:memcached協議
文本格式
二進制格式

命令:
統計類:stats, stats items, stats slabs, stats sizes
存儲類:set, add, replace, append, prepend
命令格式:<command name> <key> <flags> <exptime> <bytes>
<cas unique>
檢索類:get, delete, incr/decr
清空:flush_all

示例:
telnet> add KEY <flags> <expiretime> <bytes> \r
telnet> VALUE

memcached程序的常用選項:
-m <num>:Use <num> MB memory max to use for object storage; the default is 64 megabytes.
-c <num>:Use <num> max simultaneous connections; the default is 1024.
-u <username>:以指定的用戶身份來運行進程;
-l <ip_addr>:監聽的IP地址,默認為本機所有地址;
-p <num>:監聽的TCP端口, the default is port 11211.
-U <num>:Listen on UDP port <num>, the default is port 11211, 0 is off.
-M:內存耗盡時,不執行LRU清理緩存,而是拒絕存入新的緩存項,直到有多余的空間可用時為止;
-f <factor>:增長因子;默認是1.25;
-t <threads>:啟動的用於響應用戶請求的線程數;

memcached默認沒有認證機制,可借用於SASL進行認證;
SASL:Simple Authentication Secure Layer

API:
php-pecl-memcache
php-pecl-memcached
python-memcached
libmemcached
libmemcached-devel

命令行工具:
memcached-tool SERVER:PORT COMMAND

Nginx(4)

LB Cluster:
傳輸層:lvs、nginx、haproxy
應用層:nginx(http, https, smtp, pop, imap), haproxy(http), httpd(http/https), ats, perlbal, pound, …

nginx load balancer:
tcp/udp

nginx proxy:
reverse proxy:

應用程序發布:
灰度模型:
(1) 如果存在用戶會話;
從服務器上拆除會話;
(2) 新版本應用程序存在bug;
回滾;

ngx_http_proxy_module

(1) proxy_pass URL;
location, if in location, limit_except

註意:proxy_pass後面的路徑不帶uri時,其會將location的uri傳遞給後端主機;

location /uri/ {
proxy_pass http://HOST;
}

proxy_pass後面的路徑是一個uri時,其會將location的uri替換為proxy_pass的uri;
location /uri/ {
proxy_pass http://HOST/new_uri/;
}

如果location定義其uri時使用正則表達式的模式,則proxy_pass之後必須不能使用uri;
location ~|~* PATTERN {
proxy_pass http://HOST;
}

(2) proxy_set_header field value;
設定發往後端主機的請求報文的請求首部的值;

示例:
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for

(3) proxy_cache_path

proxy_cache_path path [levels=levels] [use_temp_path=on|off] keys_zone=name:size [inactive=time] [max_size=size] [loader_files=number] [loader_sleep=time] [loader_threshold=time] [purger=on|off] [purger_files=number] [purger_sleep=time] [purger_threshold=time];

(4) proxy_cache zone | off;
調用的緩存的名稱,或禁用緩存;

(5) proxy_cache_key string;
緩存條目的鍵;

(6) proxy_cache_valid [code …] time;
對各類響應碼的緩存時長;

使用示例:
定義在http{}中:
proxy_cache_path /var/cache/nginx/proxy_cache levels=1:2:1 keys_zone=pcache:10m max_size=1g;

定義在server{}及其內部的組件中:
proxy_cache pcache;
proxy_cache_key $request_uri;
proxy_cache_valid 200 302 10m;
proxy_cache_valid 301 1h;
proxy_cache_valid any 1m;

(7) proxy_cache_use_stale error | timeout | invalid_header | updating | http_500 | http_502 | http_503 | http_504 | http_403 | http_404 | off …;

(8) proxy_connect_timeout
proxy_read_timeout
proxy_send_timeout

(9) proxy_buffer_size
proxy_buffering
proxy_buffers

ngx_http_headers_module
The ngx_http_headers_module module allows adding the “Expires” and “Cache-Control” header fields, and arbitrary fields, to a response header.

(1) add_header name value [always];
向響應報文中添加自定義首部;

可用上下文:http, server, location, if in location

add_header X-Via $server_addr;
add_header X-Accel $server_name;

(2) expires [modified] time;
expires epoch | max | off;

用於定義Expire或Cache-Control首部的值,或添加其它自定義首部;

回顧:
LB Cluster:
傳輸層:lvs, nginx(stream), haproxy(mode tcp)
應用層:
http/https:nginx(upstream), haproxy(mode http), httpd, ats, perlbal, pound, …

lvs:
類型:nat/dr/tun/fullnat
算法:
靜態:rr, wrr, sh, dh
動態:lc, wlc, sed, nq, lblc, lblcr

session保持:
session sticky(SourceIP/Cookie)
session replication cluster
session server(redis/…)

Nginx:
web:web server, web reverse proxy
mail:mail reverse proxy
tcp/udp:stream module

ngx_http_proxy_module
proxy_path

proxy_cache_path
proxy_cache
proxy_cache_key
proxy_cache_valid
proxy_cache_methods

Nginx(4)

ngx_http_upstream_module
The ngx_http_upstream_module module is used to define groups of servers that can be referenced by the proxy_pass, fastcgi_pass, uwsgi_pass, scgi_pass, and memcached_pass directives.

(1) upstream name { … }
定義後端服務器組;引入一個新的上下文;只能用於http{}上下文中;

默認的調度方法是wrr;

(2) server address [parameters];
定義服務器地址和相關的參數;
地址格式:
IP[:PORT]
HOSTNAME[:PORT]
unix:/PATH/TO/SOME_SOCK_FILE

參數:
weight=number
權重,默認為1;
max_fails=number
失敗嘗試的最大次數;
fail_timeout=time
設置服務器為不可用狀態的超時時長;
backup
把服務器標記為“備用”狀態;
down
手動標記其為不可用;

(3) least_conn;
最少連接調度算法; 當server擁有不同的權重時為wlc;當所有後端主機的連接數相同時,則使用wrr進行調度;

(4) least_time header | last_byte;
最短平均響應時長和最少連接;
header:response_header;
last_byte: full_response;

僅Nginx Plus有效;

(5) ip_hash;
源地址hash算法;能夠將來自同一個源IP地址的請求始終發往同一個upstream server;

(6) hash key [consistent];
基於指定的key的hash表實現請求調度,此處的key可以文本、變量或二者的組合;

consistent:參數,指定使用一致性hash算法;

示例:
hash $request_uri consistent
hash $remote_addr
hash $cookie_name

(7) keepalive connections;
可使用長連接的連接數量;

(8) health_check [parameters];
定義對後端主機的健康狀態檢測機制;只能用於location上下文;

可用參數:
interval=time:檢測頻率,默認為每隔5秒鐘;
fails=number:判斷服務器狀態轉為失敗需要檢測的次數;
passes=number:判斷服務器狀態轉為成功需要檢測的次數;
uri=uri:判斷其健康與否時使用的uri;
match=name:基於指定的match來衡量檢測結果的成敗;
port=number:使用獨立的端口進行檢測;

僅Nginx Plus有效;

(9) match name { … }
Defines the named test set used to verify responses to health check requests.
定義衡量某檢測結果是否為成功的衡量機制;

專用指令:
status:期望的響應碼;
status CODE
status ! CODE

header:基於響應報文的首部進行判斷
header HEADER=VALUE
header HEADER ~ VALUE

body:基於響應報文的內容進行判斷
body ~ “PATTERN”
body !~ “PATTERN”

僅Nginx Plus有效;

博客作業:以上所有內容;
課外實踐:實踐tengine和Openresty;

ngx_stream_core_module

The ngx_stream_core_module module is available since version 1.9.0. This module is not built by default, it should be enabled with the –with-stream configuration parameter.

(1) listen address:port [ssl] [udp] [backlog=number] [bind] [ipv6only=on|off] [reuseport] [so_keepalive=on|off|[keepidle]:[keepintvl]:[keepcnt]];
監聽的端口;
默認為tcp協議;
udp: 監聽udp協議的端口;

ngx_stream_proxy_module

The ngx_stream_proxy_module module (1.9.0) allows proxying data streams over TCP, UDP (1.9.13), and UNIX-domain sockets.

(1) proxy_pass address;
Sets the address of a proxied server. The address can be specified as a domain name or IP address, and a port or as a UNIX-domain socket path.

(2) proxy_timeout timeout;
Sets the timeout between two successive read or write operations on client or proxied server connections. If no data is transmitted within this time, the connection is closed.

默認為10m;

(3) proxy_connect_timeout time;
Defines a timeout for establishing a connection with a proxied server.

設置nginx與被代理的服務器嘗試建立連接的超時時長;默認為60s;

示例:
stream {
upstream sshsrvs {
server 192.168.10.130:22;
server 192.168.10.131:22;
hash $remote_addr consistent;
}

server {
listen 172.16.100.6:22202;
proxy_pass sshsrvs;
proxy_timeout 60s;
proxy_connect_timeout 10s;
}
}

編譯安裝:
前提:開發環境,包括nginx編譯要啟用的功能依賴到的開發庫;

yum groupinstall “Development Tools” “Server Platform Development”

yum -y pcre-devel openssl-devel

編譯過程:

./configure –prefix=/usr/local/nginx –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 –user=nginx –group=nginx –with-http_ssl_module –with-http_stub_status_module –with-http_flv_module –with-http_mp4_module –with-threads –with-file-aio

make && make install

課程實踐:
nginx–> AMPs(wordpress)
nginx–> FPMs(wordpress)

nginx–> images servers ( imgs.magedu.com)
location ~* .(jpg|png|gif|jpeg)$ {

}
dynamic content servers (shop.magedu.com)
location ~* .php$ {

}

location / {

}

自定義錯誤404和5xx錯誤頁,文本靜態內容傳輸壓縮;

Nginx的配置3