Linux nginx服务之反向代理

                   Linux nginx服务之反向代理

Nginx服务之反向代理:

GSLB:Global Service LB 全局服务负载均衡:

SLB:Service LB

应用程序发布:

灰度模型:

 

ngx_http_proxy_module模块:

 1、proxy_pass URL;

Context: location, if in location, limit_except

 

注意:proxy_pass后面的路径不带uri时,其会将location的uri传递给后端主机;

server {

…

server_name HOSTNAME;

location /uri/ {

proxy_pass http://hos[:port];

}

…

  }

http://HOSTNAME/uri –> http://host/uri 

blob.png

 proxy_pass后面的路径是一个uri时,其会将location的uri替换为proxy_pass的uri;

server {

…

server_name HOSTNAME;

location /uri/ {

proxy_pass  http://host/new_uri/;

}

…

}

http://HOSTNAME/uri/ –> http://host/new_uri/

blob.png

如果location定义其uri时使用了正则表达式的模式,则proxy_pass之后必须不能使用uri; 用户请求时传递的uri将直接附加代理到的服务的之后;

    server {

…

server_name HOSTNAME;

location ~|~* /uri/ {

proxy_pass http://host;

}

…

  }

http://HOSTNAME/uri/ –> http://host/uri/;

blob.png

2、proxy_set_header field value;

设定发往后端主机的请求报文的请求首部的值;Context: http, server, location

   proxy_set_header X-Real-IP  $remote_addr;

   proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

 示例:

   让后台realserver主机记录客户端访问真正的地址,而不是nginx反向代理服务器的IP:

   在nginx反向代理服务器上设置:

blob.png

blob.png

 在后台realserver httpd服务器上设置LogFormat 

blob.png

blob.png

3、proxy_cache_path :只能用于http配置段中;

定义可用于proxy功能的缓存;Context: http

proxy_cache_path path[levels=levels]  keys_zone=name:size  [inactive=time] [max_size=size]  

4、proxy_cache zone | off;

指明要调用的缓存,或关闭缓存机制;Context: http, server, location

 

5、 proxy_cache_key string;

缓存中用于“键”的内容;

默认值:proxy_cache_key $scheme$proxy_host$request_uri;

 

6、proxy_cache_valid [code …] time;

定义对特定响应码的响应内容的缓存时长;

 示例:

   在nginx主配置文件中定义可用于proxy功能的缓存:

blob.png

在nginx默认配置文件中指明要调用的缓存或关闭缓存:

blob.png

blob.png

7、proxy_cache_use_stale

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

  当后端服务器出现故障时,后端服务器是何种故障才提供缓存中的内容响应给客户端。

8、proxy_cache_methods GET | HEAD | POST …;

   为那些请求方法去检查缓存:默认为GET、HEAD、POST没有什么意义

If the client request method is listed in this directive then the response will be cached. “GET” and “HEAD” methods are always added to the list, though it is recommended to specify them explicitly. 

9、proxy_hide_header field;

   指明要隐藏的head

By default, nginx does not pass the header fields “Date”, “Server”, “X-Pad”, and “X-Accel-…” from the response of a proxied server to a client. The proxy_hide_header directive sets additional fields that will not be passed.

10、proxy_connect_timeout time;

    设置代理连接时长,默认为60s,不能超过75s。

Defines a timeout for establishing a connection with a proxied server. It should be noted that this timeout cannot usually exceed 75 seconds.

 

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];

   向响应报文中添加首部信息;

   添加自定义首部;

add_header X-Via  $server_addr;  显示代理服务器的IP地址;

add_header X-Accel $server_name; 显示代理服务器的主机名;

blob.png

blob.png

指明此次访问的网页是由哪个ip地址的服务器代理的。

blob.png

blob.png

2、expires [modified] time;

expires epoch | max | off;

用于定义Expire或Cache-Control首部的值;

ngx_http_upstream_module模块

   定义realserver服务组

   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]

blob.png

blob.png

在nginx的默认配置文件中定义反向代理的后端服务器组的组名websrvs:

blob.png

blob.png

 parameters(参数):

weight=number

权重,默认为1;

max_fails=number

失败尝试最大次数;超出此处指定的次数时,server将被标记为不可用;

            可以对后台服务器的健康状态做检测

fail_timeout=time

设置将服务器标记为不可用状态的超时时长;

max_conns

当前的服务器的最大并发连接数;

backup

将服务器标记为“备用”,即所有服务器均不可用时此服务器才启用;

down

标记为“不可用”;

blob.png

3、least_conn;

最少连接调度算法,当server拥有不同的权重时其为wlc;

4、 ip_hash;

源地址hash调度方法;

 

5、consistent_hash;

   一致性hash调度;

 我们举个例子来说明一致性哈希的好处。

 假设后端集群包含三台缓存服务器,A、B、C。

 请求r1、r2落在A上。

 请求r3、r4落在B上。

 请求r5、r6落在C上。

 使用一致性哈希时,当缓存服务器B宕机时,r1/r2会仍然落在A上,r5/r6会仍然落在C 上,

 也就是说这两台服务器上的缓存都不会失效。r3/r4会被重新分配给A或者C,并产生回源。

 使用其它算法,当缓存服务器B宕机时,r1/r2不再落在A上,r5/r6不再落在C上了。

 也就是说A、B、C上的缓存都失效了,所有的请求都要回源。

blob.png

blob.png

5、hash key [consistent];

基于指定的key的hash表来实现对请求的调度,此处的key可以直接文本、变量或二者的组合;

作用:将请求分类,同一类请求将发往同一个real server;

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

示例:

hash $request_uri consistent; 将来自同一uri的请求始终发往同一个real server

hash $remote_addr;将来自同一个客户端的IP地址请求始终发往同一个real server

blob.png

6、keepalive connections;

   定义nginx代理服务器和后端服务器的保持连接。

为每个worker进程保留的空闲的长连接数量;

 

nginx的其它的二次发行版:

  tengine

  OpenResty

ngx_stream_core_module模块 放置在main配置段中 core:核心 stream:流动

   模拟反代基于tcp或udp的服务连接,即工作于传输层的反代或调度器;

   和http同等级的配置段,stream要放置在main配置段中。

 

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;

}

}

blob.png

blob.png

注意:自定义stream基于tcp或udp反向代理时,需要把nginx的主配置文件中的http配置段注释掉。

blob.png

blob.png

blob.png

2、listen

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

 

memcached缓存服务器:

   缓存服务器:

 缓存:cache,无持久存储功能;

 bypass缓存

 k/v cache,仅支持存储流式化数据;

LiveJournal旗下的Danga Interactive研发,

    特性:

k/v cache:仅可序列化数据;存储项:k/v;

        k:存放于内存的hash表中;(k是哈希的文件名)

        v:存放于内存中的数据;(v是数据)

智能性一半依赖于客户端(调用memcached的API开发程序),一半依赖于服务端;

分布式缓存:互不通信的分布式集群;

分布式系统请求路由方法:取模法,一致性哈希算法;

算法复杂度:O(1)

           O(1)就是说n很大的时候,复杂度基本就不增长了,基本就是个常量c;

清理过期缓存项:

缓存耗尽:LRU

缓存项过期:惰性清理机制

 

安装配置:

由CentOS 7 base仓库直接提供:

监听的端口:11211/tcp, 11211/udp ,以tcp使用的最多。

    主程序:/usr/bin/memcached

配置文件:/etc/sysconfig/memcached  memcached的环境配置文件。

Unit File:memcached.service

         启动memcached:

协议格式:memcached协议

文本格式

二进制格式:编码效率更高;

    

命令:

统计类:stats, stats items, stats slabs, stats sizes

存储类:set, add, replace, append, prepend

            set:表示key有值就修改,没有值就新创建。

            add:表示新创建key值。

            replace:

            append:在已有key值之后附加新值。

            prepend:在已有key值的前面追加新值。

命令格式:<command name> <key> <flags> <exptime> <bytes>  

<cas unique>

检索类:get, delete, incr/decr

            get:获取key值数据。

            delete:删除数据。

            incr:把已有的值加1。

            decr:把已有的值减1。

blob.png

清空:flush_all:清空整个缓存。

blob.png

示例:

telnet> add KEY <flags> <expiretime> <bytes> \r

telnet> VALUE

blob.png

blob.png

blob.png

blob.png

blob.png

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的增长因子过程:

blob.png

memcached默认没有认证机制,可借用于SASL进行认证;

SASL:Simple Authentication Secure Layer

API:

php-pecl-memcache 可能需要依赖epel yum源进行安装。

php-pecl-memcached 可能需要依赖epel yum源进行安装。

python-memcached

libmemcached

libmemcached-devel

命令行工具:

   memcached-tool  SERVER:PORT  COMMAND

blob.png

实验测试:

  使用nginx反向代理,后端httpd realserver组:

  实验环境:

  测试客户机:

  client客户机:IP :192.168.3.7;

  nginx反向代理服务器:

     配置两块网卡,网卡1:ip:192.168.3.5 网卡2:192.168.22.1

  后台realserver配置:

  realserver (1)httpd服务器:serverIP:192.168.22.2  gateway:192.168.22.1:

     在realserver(1)中配置http服务器 upstream server 1

  realserver (2)httpd服务器:serverIP:192.168.22.3  gateway:192.168.22.1:

     在realserver(2)中配置http服务器 upstream server 2

 

1)在realserver(1)上搭建http服务:

blob.png

blob.png

2)在realserver(2)上搭建http服务和nginx服务器,nginx服务器监听8080端口:

blob.png

blob.png

  在realserver(2)上 配置nginx服务器监听8080端口:

配置默认主页为:

blob.png

blob.png

blob.png

blob.png

3)配置nginx反向代理服务器:

在nginx的主配置文件中的http配置段中配置upstream 后端服务器组:

blob.png

 在nginx的默认配置文件中定义反向代理的后端服务器组的组名websrvs:

blob.png

blob.png

nginx配合完成之后使用nginx -t 检查一下语法是否正确;

如果语法没有错误就可以使用 nginx -s reload 或 systemctl  restart nginx.service 重载或重启服务。

4)在client 192.168.3.7 客户端 主机上测试请求后端realserver httpd服务器组:

blob.png

5)关闭 realserver(1)和realserver(2)上的httpd服务进行测试backup主机服务器:

 或是在/etc/nginx/nginx.conf的主配置文件中在upstream配置段中将realserver1、2标记为down。

blob.png

blob.png

原创文章,作者:zhengyibo,如若转载,请注明出处:http://www.178linux.com/59610

赞 (0)
zhengyibozhengyibo
上一篇 2016-11-18 18:29
下一篇 2016-11-18 19:01

相关推荐

  • 浅谈DNS基本原理以及实现方法(一)

     DNS(Domain Name System,域名系统),是目前互联网上最不可或缺的服务器之一,我们在互联网从访问一个网站,到发送一封电子邮件,再到定位域中的域控制器,无时无刻不再使用着DNS为我们提供的服务,那为什么我们会需要这样一个服务那?带着这样一个疑问让我们先来认识一下什么是DNS吧  DNS最核心的工作就是域名解析,也就是把计…

    Linux干货 2015-12-15
  • 四大开源协议比较:BSD、Apache、GPL、LGPL

          现今存在的开源协议很多,而经过Open Source Initiative组织通过批准的开源协议目前有58种。我们现在常见的开源协议如BSD, GPL, LGPL,MIT等都是OSI批准的协议。如果要开源自己的代码,最好也是选择这些被批准的开源协议。   这里我们来看四种最常用的开源协议及它们的适用范围,供那些准备开…

    系统运维 2016-08-15
  • 震惊!!iptables还能这样用!

    基本语法:iptables [-t 表] [操作命令] [链][规则匹配器][-j 目标动作] 系统的INPUT和OUTPUT默认策略为DROP; # iptables -P INPUT DROP # iptables -P OUTPUT DROP 1、限制本地主机的web服务器在周一不允许访问;新请求的速率不能超过100个每秒;web服务器包含了admin…

    系统运维 2017-04-18
  • rsyslog同步history日志

    前言   由于公司业务是由公司内部开人员及外包团队共同开发,所以需要使用rsyslog对history日志做收集、审计。虽然搭建及配置非常简单,但是在日常运维工作中很实用,所以记录下,方便日后快速搭建。如果有错误,望大神指正。 syslog简介 syslog是Linux系统默认的日志守护进程。默认的syslog配置文件是/etc/sysl…

    Linux干货 2015-04-03
  • 关于软件包管理

            软件包管理 CentOS系统上使用rpm命令管理程序包 安装、卸载、升级、查询、检验、数据库维护 rpm安装:         rpm {-i|–install} [安装-选项] 打包;包         -h …

    系统运维 2016-08-30
  • IP地址的三种表示格式及在Socket编程中的应用

       使用TCP/IP协议进行网络应用开发的朋友首先要面对的就是对IP地址信息的处理。IP地址其实有三种不同的表示格式:        1)Ascii(网络点分字符串)-        2) 网络地址(32位无符号整形,网络字节序,大头) &nbsp…

    Linux干货 2015-04-10

评论列表(1条)

  • Cornelia
    Cornelia 2017-04-24 06:10

    Sehr geehrte Damen und Herren,bitte tragen Sie mich in den Hydrogeit-Newsletter ein. Leider führt die Eigeninitiative unter Verwendung des vorgesehenen Formulars zu einem Dat.rbankfehleneBesten Dank!Mit freundlichen GrüßenHolger Krings