nginx基础&nginx正向代理&nginx反向代理

1.1nginx基础

1.1.1 什么是nginx

  • 部署web项目的容器(部署你们写的项目),常见的web容器有:nginx,Apache,Tomcat
  • nginx官方宣称可以处理十万并发(处理静态资源的时候应该是可以达到这个水平)

1.1.2 nginx为什么能处理高并发

  • nginx高并发原理( 多进程+epoll实现高并发 )
    • Nginx 在启动后,会有一个 master 进程和多个相互独立的 worker 进程。
    • 每个子进程只有一个线程(协程),采用的 IO多路复用模型epoll,实现高并发。

1.1.3 epoll能实现高并发原理

  • epoll() 中内核则维护一个链表,epoll_wait 方法可以获取到链表长度,不为0就知道文件描述符准备好了。

  • 在内核实现中 epoll 是根据每个 sockfd 上面的与设备驱动程序建立起来的回调函数实现的。

  • 某个 sockfd 上的事件发生时,与它对应的回调函数就会被调用,来把这个 sockfd 加入链表,其他处于“空闲的”状态的则不会。

  • epoll上面链表中获取文件描述,这里使用内存映射(mmap)技术, 避免了复制大量文件描述符带来的开销

  • 内存映射(mmap):内存映射文件,是由一个文件到一块内存的映射,将不必再对文件执行I/O操作

  • 不仅取消了1024这个最大连接限制

  • 而且能告诉用户程序哪一个是活跃的

1.1.4 nginx和apache比较

1)nginx相对于apache的优点

  1. 轻量级,同样起web 服务,比apache 占用更少的内存及资源

  2. 抗并发,nginx 处理请求是异步非阻塞的,而apache 则是阻塞型的,在高并发下nginx 能保持低资源低消耗高性能

  3. 高度模块化的设计,编写模块相对简单,社区活跃,各种高性能模块出品迅速啊

2)apache 相对于nginx 的优点

  1. apache 更为成熟,少 bug ,稳定性好

  2. rewrite ,比nginx 的rewrite 强大

  3. 模块超多,基本想到的都可以找到

1.2 nginx正向代理 & 反向代理

12.1、正向代理

  1. 我访问不了某网站,但是我能访问一个代理服务器,这个代理服务器呢,他能访问那个我不能访问的网站

  2. 于是我先连上代理服务器,告诉他我需要那个无法访问网站的内容,代理服务器去取回来,然后返回给我。

  3. 客户端必须设置正向代理服务器,当然前提是要知道正向代理服务器的IP地址,还有代理程序的端口。

  4. 例如之前使用过这类软件例如CCproxy,http://www.ccproxy.com/ 需要在浏览器中配置代理的地址。

  • 正向代理作用
     1)访问原来无法访问的资源,如google
     2) 可以做缓存,加速访问资源
     3)对客户端访问授权,上网进行认证
     4)代理可以记录用户访问记录(上网行为管理),对外隐藏用户信息

1.2.2、反向代理

  1. 反向代理对用户透明,客户端无需任何配置即可访问服务。

  2. 实际运行方式是指以代理服务器来接受internet上的连接请求,然后将请求转发给内部网络上的服务器。

  3. 并将从服务器上得到的结果返回给internet上请求连接的客户端,此时代理服务器对外就表现为一个服务器。

1.2.3、反向代理使用场景

1)保证内网的安全,可以使用反向代理提供WAF功能,阻止web攻击

例:大型网站,通常将反向代理作为公网访问地址,Web服务器是内网

在这里插入图片描述
2)负载均衡,通过反向代理服务器来优化网站的负载
在这里插入图片描述

1.3 nginx常用配置

1、nginx配置文件注释

  • ngingx配置文件及注释
#运行用户
user nobody;
#启动进程,通常设置成和cpu的数量相等
worker_processes  1;
 
#全局错误日志及PID文件
#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;
 
#pid        logs/nginx.pid;
 
#工作模式及连接数上限
events {
    #epoll是多路复用IO(I/O Multiplexing)中的一种方式,
    #仅用于linux2.6以上内核,可以大大提高nginx的性能
    use   epoll; 
 
    #单个后台worker process进程的最大并发链接数    
    worker_connections  1024;
 
    # 并发总数是 worker_processes 和 worker_connections 的乘积
    # 即 max_clients = worker_processes * worker_connections
    # 在设置了反向代理的情况下,max_clients = worker_processes * worker_connections / 4  为什么
    # 为什么上面反向代理要除以4,应该说是一个经验值
    # 根据以上条件,正常情况下的Nginx Server可以应付的最大连接数为:4 * 8000 = 32000
    # worker_connections 值的设置跟物理内存大小有关
    # 因为并发受IO约束,max_clients的值须小于系统可以打开的最大文件数
    # 而系统可以打开的最大文件数和内存大小成正比,一般1GB内存的机器上可以打开的文件数大约是10万左右
    # 我们来看看360M内存的VPS可以打开的文件句柄数是多少:
    # $ cat /proc/sys/fs/file-max
    # 输出 34336
    # 32000 < 34336,即并发连接总数小于系统可以打开的文件句柄总数,这样就在操作系统可以承受的范围之内
    # 所以,worker_connections 的值需根据 worker_processes 进程数目和系统可以打开的最大文件总数进行适当地进行设置
    # 使得并发总数小于操作系统可以打开的最大文件数目
    # 其实质也就是根据主机的物理CPU和内存进行配置
    # 当然,理论上的并发总数可能会和实际有所偏差,因为主机还有其他的工作进程需要消耗系统资源。
    # ulimit -SHn 65535
 
}
 
 
http {
    #设定mime类型,类型由mime.type文件定义
    include    mime.types;
    default_type  application/octet-stream;
    #设定日志格式
    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 函数(zero copy 方式)来输出文件,
    #对于普通应用,必须设为 on,
    #如果用来进行下载等应用磁盘IO重负载应用,可设置为 off,
    #以平衡磁盘与网络I/O处理速度,降低系统的uptime.
    sendfile     on;
    #tcp_nopush     on;
 
    #连接超时时间
    #keepalive_timeout  0;
    keepalive_timeout  65;
    tcp_nodelay     on;
 
    #开启gzip压缩
    gzip  on;
    gzip_disable "MSIE [1-6].";
 
    #设定请求缓冲
    client_header_buffer_size    128k;
    large_client_header_buffers  4 128k;
 
 
    #设定虚拟主机配置
    server {
        #侦听80端口
        listen    80;
        #定义使用 www.nginx.cn访问
        server_name  www.nginx.cn;
 
        #定义服务器的默认网站根目录位置
        root html;
 
        #设定本虚拟主机的访问日志
        access_log  logs/nginx.access.log  main;
 
        #默认请求
        location / {
            
            #定义首页索引文件的名称
            index index.php index.html index.htm;   
 
        }
 
        # 定义错误提示页面
        error_page   500 502 503 504 /50x.html;
        location = /50x.html {
        }
 
        #静态文件,nginx自己处理
        location ~ ^/(images|javascript|js|css|flash|media|static)/ {
            
            #过期30天,静态文件不怎么更新,过期可以设大一点,
            #如果频繁更新,则可以设置得小一点。
            expires 30d;
        }
 
        #PHP 脚本请求全部转发到 FastCGI处理. 使用FastCGI默认配置.
        location ~ .php$ {
            fastcgi_pass 127.0.0.1:9000;
            fastcgi_index index.php;
            fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
            include fastcgi_params;
        }
 
        #禁止访问 .htxxx 文件
            location ~ /.ht {
            deny all;
        }
 
    }
}

2、nginx配置举例

  • ngingx/conf/ngingx.conf 主配置文件
user  work;
worker_processes 8;
worker_rlimit_nofile 65535;

error_log  logs/error.log warn;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

pid        logs/nginx.pid;

events {
    use epoll;
    worker_connections  65535;
}

# load modules compiled as Dynamic Shared Object (DSO)
#
#dso {
#    load ngx_http_fastcgi_module.so;
#    load ngx_http_rewrite_module.so;
#}
http {
    include       mime.types;
    default_type  application/octet-stream;

    server_names_hash_bucket_size 128;

    sendfile        on;
    tcp_nopush      on;
    tcp_nodelay     on;

    fastcgi_connect_timeout 5;
    fastcgi_send_timeout 10;
    fastcgi_read_timeout 10;
    fastcgi_buffer_size 64k;
    fastcgi_buffers 4 64k;
    fastcgi_busy_buffers_size 128k;
    fastcgi_temp_file_write_size 128k;

    #keepalive_timeout  0;
    keepalive_timeout  60;
    keepalive_requests 1024;
    client_header_buffer_size 4k;
    large_client_header_buffers 4 32k;
    client_max_body_size 10m;

    client_body_buffer_size 512k;
    client_body_timeout 600;
    client_header_timeout 600;
    send_timeout 600;

    proxy_connect_timeout   1000ms;
    proxy_send_timeout      2000000ms;
    proxy_read_timeout      2000000ms;
    proxy_buffers           64 8k;
    proxy_busy_buffers_size    128k;
    proxy_temp_file_write_size 64k;
    proxy_redirect off;
    #proxy_next_upstream off ;

    gzip on;
    gzip_min_length 1k;
    gzip_buffers 4 16k;
    gzip_http_version 1.0;
    gzip_comp_level 2;
    gzip_types text/plain application/x-javascript text/css application/xml;
    gzip_vary on;
    add_header X-Frame-Options "ALLOW-FROM  http://cloud.njsig.cn";
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Real-Port $remote_port;
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
        '$status $body_bytes_sent "$http_referer" "$http_cookie" "$http_user_agent" '
        '$request_time $remote_addr $server_addr $upstream_addr $host '
        '"$http_x_forwarded_for" $upstream_response_time';

    set_real_ip_from 10.0.0.0/8;
    real_ip_header X-Real-IP;

    #example
#     server {
#        listen 8000;
#        server_name www;
#        access_log logs/access.log  main;
#        location / {
#            proxy_pass http://127.0.0.1:8001;
#        }
#
#
#      }
    include vhosts/*.conf;
    }
#####
  • ngingx/conf/vhosts/opwf.conf django项目简单配置
server {
        listen 80;
        server_name aaa.test.com bbb.test.com;
        access_log  /home/work/nginx/logs/opwf_access.log main;
        location / {
            proxy_pass http://127.0.0.1:8001;
        }
}
  • ngingx/conf/vhosts/vue.conf VUE项目简单配置

server {
        listen 80;
        server_name ccc.test.com;
        access_log  /home/work/nginx/logs/nj1_access.log main;
        root /home/work/project/frontopwf/dist;
        location / {
                try_files $uri $uri/ @router;
        }
        location @router {
                rewrite ^.*$ /index.html last;
        }
}

1.4 nginx负载均衡配置

1、搭建实验环境(使用docker部署两台nginx容器)

1)使用搭建第一台nginx服务
[root@linux-node4 ~]# docker container run -d --name web01 -p 81:80 nginx
测试访问:http://192.168.56.14:81/
root@c58a7f1fb89d:/# docker exec -it web01 bash
root@c58a7f1fb89d:/# echo web01 > /usr/share/nginx/html/index.html
2)使用docker搭建第二台nginx服务
[root@linux-node4 ~]# docker container run -d --name web02 -p 82:80 nginx
测试访问:http://192.168.56.14:82/
root@a3440d30f27c:/#  docker exec -it web02 bash
root@a3440d30f27c:/#  echo web02 > /usr/share/nginx/html/index.html

2、法1:默认轮训(在真实主机中安装nginx并配置负载均衡)

轮训每个请求按时间顺序逐一分配到不同的后端服务器,如果后端服务器down掉,能自动剔除。

复制代码
[root@linux-node4 ~]# yum -y install nginx
[root@linux-node4 ~]# vim /etc/nginx/nginx.conf
#### 修改nginx.conf 默认是轮训 ####

'''
# 1. upstream是自己写的,一定要放在server外面
upstream myservers {
    server 192.168.56.14:81;
    server 192.168.56.14:82;
}

# 2. server其实默认已经有一个,只需要修改location中配置,指定转发代理即可
server {
    location / {
       proxy_pass http://myservers;
    }
}
'''
[root@linux-node4 nginx]# systemctl start nginx 

3、负载均衡常用配置梳理

1、轮询(默认)
每个请求按时间顺序逐一分配到不同的后端服务器,如果后端服务器down掉,能自动剔除。

upstream backserver {
    server 192.168.0.14;
    server 192.168.0.15;
}

2、权重 weight
指定轮询几率,weight和访问比率成正比,用于后端服务器性能不均的情况。

upstream backserver {
    server 192.168.0.14 weight=3;
    server 192.168.0.15 weight=7;
}

3、ip_hash( IP绑定)
上述方式存在一个问题就是说,在负载均衡系统中,假如用户在某台服务器上登录了,那么该用户第二次请求的时候,因为我们是负载均衡系统,
每次请求都会重新定位到服务器集群中的某一个,那么已经登录某一个服务器的用户再重新定位到另一个服务器,其登录信息将会丢失,这样显然是不妥的。
我们可以采用ip_hash指令解决这个问题,如果客户已经访问了某个服务器,当用户再次访问时,会将该请求通过哈希算法,自动定位到该服务器。
每个请求按访问ip的hash结果分配,这样每个访客固定访问一个后端服务器,可以解决session的问题。

upstream backserver {
    ip_hash;
    server 192.168.0.14:88;
    server 192.168.0.15:80;
}

4、fair(第三方插件)
按后端服务器的响应时间来分配请求,响应时间短的优先分配。

upstream backserver {
    server server1;
    server server2;
    fair;
}

5、url_hash(第三方插件)
按访问url的hash结果来分配请求,使每个url定向到同一个后端服务器,后端服务器为缓存时比较有效。

upstream backserver {
    server squid1:3128;
    server squid2:3128;
    hash $request_uri;
    hash_method crc32;
}
  • 反向代理和web服务器的区别
    • 反向代理服务器:通过给你uostream参数配置,proxy_pass
    • web服务器:web服务器应该部署我们真实项目(uwsgi+django+nginx)
    • 几台反向代理服务器:没有使用LVS等负载均衡技术,那么只有一台负载均衡服务器
    • 反向代理服务器部署nginx后台为什么也部署nginx,提高每个web服务器处理能力
发布了37 篇原创文章 · 获赞 7 · 访问量 1191

猜你喜欢

转载自blog.csdn.net/Hanmin_hm/article/details/104604910
今日推荐