Nginx 基础

Nginx 基础

1、nginx 基本概念
(1) 什么是nginx, 它是用来做什么的
Nginx 是一款轻量级的web服务器/反向代理服务器及电子邮件(IMAP/pop3)代理服务器,在BSD-like协议下发行。其特点是占有内存少,并发能力强,事实上nginx的并发能力确实在同类型的网页服务器中表现良好
Nginx 可以作为静态页面
(2) 反向代理
	正向代理:在客户端(浏览器)配置代理服务器,通过代理服务器进行互联网访问
	反向代理:其实客户端对代理服务器是无感知的,因为客户端不需要任何配置就可以访问,我们只需要
	将请求发送到反向代理服务器,由反向代理服务器去选择目标服务器获取数据,在返回给客户端,此时	 反向代理服务器和目标服务器对外就是一个服务器,暴露的是代理服务器地址,隐藏了真实服务器的ip		地址
(3) 负载均衡
	客服端发送多个请求到服务器,服务器处理请求,有一些可能是要与数据库进行交互,服务器处理完	后,再将结果返回给客户端。
	主要就是把请求分发到多个服务器上
(4) 动静分离
	为了加快网站的解析速度,可以把动态页面和静态页面由不同的服务器来解析,加快解析速度,降低原	 来单个服务器的压力(把静态资源放在一个服务器上,把动态资源放在另一个服务器上)
2、nginx安装、常用命令和配置文件
(1) 在linux 系统中安装 nginx
	(注:纯净的linux系统要安装cpp:
	yum -y install cpp
	可能还有安装 c++:
	yum install -y gcc-c++
	)
	在安装在nginx之前首先要安装一些依赖
		1、pcre
		2、openssl
		3、zlib
	安装方法1:
	解压后,进入解压后的目录,执行./configure  然后执行make && make install
	查看版本号 pcre-config --verson, 
	
	安装nginx 也是一样的步骤,安装完后它或自动在/usr/local下创建一个名为nginx的目录,启动程	  序在sbin目录下
(2) nginx 常用命令
	在sbin目录下执行./nginx    启动nginx
				  ./nginx -V 查看版本号
				  ./nginx -s stop 关闭nginx
				  ./nginx -s reload 从新加载
	
	查看防火墙开发的端口号:firewall-cmd --list-all
	设置开放端口号:firewall-cmd --add-service=http --permanent
				 sodu firewall-cmd --add-port=80/tcp --permanent
(3) nginx 配置文件
	配置文件在nginx/conf/nginx.conf
	配置文件由三部分组成,
第一部分:全局块,  从配置文件开始到events块之间的内容,主要会设置一些影响nginx 服务器整  	 体运行的配置指令,比如:worker_processess 的值越大,可以支持的并发就越多,但会收到硬件的	  限制
第二部分:events块, 涉及的指令主要影响nginx服务器与用户的网络连接,常用的设置包括是否开启多
	workprocess下的的网络链接进行序列化,是否允许同时接收多个网络连接,选择那种事件驱动来处理  	连接请求,每个word process 可以支持最大连接数等
	
第三部分:http块,也是nginx中配置频繁的部分,代理、缓存、日志定义等绝大多数功能和第三方模块的配置都是在配置;
		http块又分http全局块、server块,
			http全局块配置的指令包括文件引入、MIME-TYPE定义,日志自定义,连接超时时间、
			单连接请求数上线
		    server块---和虚拟机由密切的关系,每个http块可以包括多个server块,而每个server
		    块相当于一个虚拟机
		    而每个server块也分为server全局块,已及同时包含多个location块
		    
		    server全局:
		    	最常见的配置是本虚拟机主机监听配置和本虚拟机主机的名称和ip配置
		    	
		    location 块:
		    	一个server 可以配置多个location块。
		    	这主要的作用是基于nginx服务器接收到请求字符串(列如:server_name/uri-					strng),对虚拟主机名称(也可以是ip别名)之外的字符串(例如:前面的/uri-					string)进行匹配,对特定的请求进行处理。地址定向,数据缓存和答应控制等功能
		    	还有许多的第三方模块的配置也在这里进行。

3、nginx 配置实列 1-反向代理


4、nginx 配置实列 2-负载均衡



配置文件

#user  nobody;
worker_processes  1; #全局块-------------------------------------------------

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

#pid        logs/nginx.pid;


events { # events块-----------------------------------------------------------
    worker_connections  1024;
}


http { # http块---------------------------------------------------------------
    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        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;

    server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            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;
        }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    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;
    #    }
    #}

}

Nginx 的反向代理配置

实列:
1、实现的效果
	(1)在浏览器输入http://ip 跳转到linux系统的 tomcat主		页面。
	安装tomcat
	
	配置nginx的反向代理:
	在nginx进行请求转发配置(反向代理配置)
    server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   html;
            # 加上下边这一行代码
            proxy_pass http://localhost:8080;
            
            index  index.html index.htm;
        }
        
2、实现效果
	使用nginx反向代理,根据不同访问路径跳转到不同的端口服务
	设置nginx 监听端口为8001
	如:
	 访问 http://ip:8001/edu/ 直接跳转到ip:8081
	 访问 http://ip:8001/vod/ 直接跳转到ip:8080
	 
	准备两给tomcat 服务器 8080 和 8081
	tomcat配置文件的路径是conf/server.xml
	改:
	<Server port="8005" shutdown="SHUTDOWN">
  <Listener className="org.apache.catalina.startup.VersionLoggerListener" />
  为:
  <Server port="8015" shutdown="SHUTDOWN">
  <Listener className="org.apache.catalina.startup.VersionLoggerListener" />
	然后将:
	    <Connector port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" />
     改为:
     	  <Connector port="8081" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" />
               
    另一个保持不变就可以
    
    在8080 :webapps下创建edu目录在创建一个文件index.html
    在8081 :webapps下创建vod目录在创建一个文件index.html
    访问http://ip:8080/edu/index.html
    访问http://ip:8081/vod/index.html
    能访问到,说明成功
    
    
 nginx 的配置:
 在nginx/conf/nginx.conf 作相关配置
 把:
  #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}
    
   改为:
    server {
        listen       8001;
        server_name  localhost;
        
        location ~/edu/ {
            proxy_pass http://localhost:8080;
        }
        location ~/vod/ {
            proxy_pass http://localhost:8081;
        }
    }
    访问http://ip:8001/edu/index.html
    访问http://ip:8001/vod/index.html
    如果能访问,说明成功

配置Nginx的负载均衡

客服端发送多个请求到服务器,服务器处理请求,有一些可能是要与数据库进行交互,服务器处理完	后,再将结果返回给客户端。
	主要就是把请求分发到多个服务器
	
实列:
1、实现效果:
	在浏览器上输入地址 http://ip/edu/a.html 负载均衡效果
	平均分配到8080和8081的端口中去
	
	准备两台tomcat服务器,一台8080,一台8081
	在两台服务器中的webapps目录中创建edu目录 在edu目录中创	  建a.html
	
	在nginx中进行负载均衡的配置
	#gzip  on;
    upstream myserver {
        server localhost:8080;
        server localhost:8081;
    }# 这里是负载均衡的配置
    server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   html;
            proxy_pass http://myserver;#这里加的是负载				均衡的名称
            index  index.html index.htm;
        }
    访问 http://ip/edu/a.html
    能访问得到,刷新后页面变化,说明成功
    
负载均衡的策略:
1、轮询(默认)
每个请求按时间顺序逐一分配到不同的后端服务器,后果后端服务器down掉了,能自动剔除
 upstream myserver {
        server localhost:8080;
        server localhost:8081;
    }
2、权重策略:
	weight 代表权,默认为1,权重越高被分配的客户端就越多
	指定轮询的几率,weight和访问成正比,用于后端服务器性能不		均的情况。
	 upstream myserver {
        server localhost:8080 weight=5;
        server localhost:8081 weight=10;
    }
3、ip_hash
每个亲求按访问ip的hash结果分配,这样每个访客固定访问一个后端服务器,可以解决session的问题:
 upstream myserver {
 		ip_hash;
        server localhost:8080;
        server localhost:8081;
    }
4、fair 策略(第三方)
按后端服务器的响应时间来分配请求,相应时间短的优先分配。
 upstream myserver {
        server localhost:8080;
        server localhost:8081;
        fair;
    }

动静分离

为了加快网站的解析速度,可以把动态页面和静态页面由不同的服务器来解析,加快解析速度,降低原	 来单个服务器的压力(把静态资源放在一个服务器上,把动态资源放在另一个服务器上)

动静分离有两中实现方式
一种就是纯粹把静态资源文件独立成一个域名服务器,也是目前主流推崇的方案。
另一种方法就是动态和静态文件混合一起发布,通过nginx来分开。

通过loaction指定不同的后缀名 实现不同的的请求转发,通过expires 参数设置,可以使浏览器缓存过期时间,减少服务器之前的请求和流量。具体 Expires 定义:是给一个资源设定一个过期时间,也就是说无需去服务器验证,直接通过浏览器自身的确认是否过期即可,所以不会产生额外的流量。此种方法非常适合不经常变动的资源。(如果经常更新的文件,不建议使用Expires来缓存), 设置3d 表示这3天访问这个URL,发送一个请求,对比服务器该文件最后的时间没有变化,则不会从服务器抓取,返回状态码为304,如果由修改,则直接从服务器从新加载,返回状态码为200。

动静分离的配置:
	在一个linux服务器的根目录下创建一些目录来存放静态资源
	
	通过nginx配置来访问静态资源
	
	在nginx的配置文件中进行如下的配置
	server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location /www/ {
            root   /data/;
            index  index.html index.htm;
        }
        location /image/ {
            root /data/;
            autoindex on;
        }

Nginx 高可用

高可用-->准备多给nginx服务器,一台为主设备(MASter),其余的为从属设备(BACKUP) 来应对当MASTER down机时,BACKUP继续工作,
需要用到keepalived如今来对他们进行控制, 还要绑定一个固定的虚拟ip。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-UNkemZG7-1607655076127)(C:\Users\admin\AppData\Roaming\Typora\typora-user-images\image-20201130102315341.png)]

1、配置的准备工作:
	需要两台以上的服务器
	都要安装有nginx
	都要安装keepalived
	yum install keepalived
	
	安装nginx的依赖环境:
	yum install make zlib zlib-devel gcc-c++ libtool openssl-devel
	
	用yum 安装的keepalived 在/etc/keepalived里有一个文件keepalived.conf 配置文件
	
	
2、高可用配置
	以上的工作都完成后,编写检查脚本
	主,备机都在/usr/local/src/nginx_check.sh 添加上如下的脚本:
	#!/bin/bash
	A=`ps -C nginx --no-header | wc -l`
	if [ $A -eq 0 ];then
		/usr/local/nginx/sbin/nginx
		sleep 2
		if [ `ps -C nginx --no-header | wc -l` -eq 0];then
			killall keepalived
		fi
		
	fi
	
	把两台服务器启动起来就可以进行测试了
	启动两台nginx服务器
	
	启动 keepalived: systemctl start keepalived.service
	
	

	

配置文件的内容

#源配置
! Configuration File for keepalived

global_defs {
   notification_email {
     acassen@firewall.loc
     failover@firewall.loc
     sysadmin@firewall.loc
   }
   notification_email_from Alexandre.Cassen@firewall.loc
   smtp_server 192.168.200.1
   smtp_connect_timeout 30
   router_id LVS_DEVEL
   vrrp_skip_check_adv_addr
   vrrp_strict
   vrrp_garp_interval 0
   vrrp_gna_interval 0
}

vrrp_instance VI_1 {
    state MASTER
    interface eth0
    virtual_router_id 51
    priority 100
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass 1111
    }
    virtual_ipaddress {
        192.168.200.16
        192.168.200.17
        192.168.200.18
    }
}

virtual_server 192.168.200.100 443 {
    delay_loop 6
    lb_algo rr
    lb_kind NAT
    persistence_timeout 50
    protocol TCP

    real_server 192.168.201.100 443 {
        weight 1
        SSL_GET {
            url {
              path /
              digest ff20ad2481f97b1754ef3e12ecd3a9cc
            }
            url {
              path /mrtg/
              digest 9b3a0c85a887a256d6939da88aabd8cd
            }
            connect_timeout 3
            retry 3
            delay_before_retry 3
        }
    }
}

virtual_server 10.10.10.2 1358 {
    delay_loop 6
    lb_algo rr
    lb_kind NAT
    persistence_timeout 50
    protocol TCP

    sorry_server 192.168.200.200 1358

    real_server 192.168.200.2 1358 {
        weight 1
        HTTP_GET {
            url {
              path /testurl/test.jsp
              digest 640205b7b0fc66c1ea91c463fac6334d
            }
            url {
              path /testurl2/test.jsp
              digest 640205b7b0fc66c1ea91c463fac6334d
            }
            url {
              path /testurl3/test.jsp
              digest 640205b7b0fc66c1ea91c463fac6334d
            }
            connect_timeout 3
            retry 3
            delay_before_retry 3
        }
    }

    real_server 192.168.200.3 1358 {
        weight 1
        HTTP_GET {
            url {
              path /testurl/test.jsp
              digest 640205b7b0fc66c1ea91c463fac6334c
            }
            url {
              path /testurl2/test.jsp
              digest 640205b7b0fc66c1ea91c463fac6334c
            }
            connect_timeout 3
            retry 3
            delay_before_retry 3
        }
    }
}

virtual_server 10.10.10.3 1358 {
    delay_loop 3
    lb_algo rr
    lb_kind NAT
    persistence_timeout 50
    protocol TCP

    real_server 192.168.200.4 1358 {
        weight 1
        HTTP_GET {
            url {
              path /testurl/test.jsp
              digest 640205b7b0fc66c1ea91c463fac6334d
            }
            url {
              path /testurl2/test.jsp
              digest 640205b7b0fc66c1ea91c463fac6334d
            }
            url {
              path /testurl3/test.jsp
              digest 640205b7b0fc66c1ea91c463fac6334d
            }
            connect_timeout 3
            retry 3
            delay_before_retry 3
        }
    }

    real_server 192.168.200.5 1358 {
        weight 1
        HTTP_GET {
            url {
              path /testurl/test.jsp
              digest 640205b7b0fc66c1ea91c463fac6334d
            }
            url {
              path /testurl2/test.jsp
              digest 640205b7b0fc66c1ea91c463fac6334d
            }
            url {
              path /testurl3/test.jsp
              digest 640205b7b0fc66c1ea91c463fac6334d
            }
            connect_timeout 3
            retry 3
            delay_before_retry 3
        }
    }
}

#修改后
! Configuration File for keepalived

global_defs {
   notification_email {
     acassen@firewall.loc
     failover@firewall.loc
     sysadmin@firewall.loc
   }
   notification_email_from Alexandre.Cassen@firewall.loc
   smtp_server 192.168.200.1
   smtp_connect_timeout 30
   router_id LVS_DEVELBACKUP # 在/etc/hosts 配置 127.0.0.1  `LVS_DEVELBACKUP 这行代码
}

vrrp_script chk_http_port {
	script "/usr/local/src/nginx_check.sh" #检查脚本路径
	
	interval 2   # 检查脚本时间间隔
	
	weight 2
}

vrrp_instance VI_1 {
    state MASTER #如果是备份服务器,将 MASTER 改为 BACKUP
    interface eth0 # 网卡
    virtual_router_id 51 #主、备机的virtual_router_id 必须相同
    priority 100  # 主、备机取值不同的优先级,主机值交大,备份机值较小
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass 1111
    }
    virtual_ipaddress {
        192.168.200.16  # VRRP H虚拟地址
    }
}


smtp_server 192.168.200.1
smtp_connect_timeout 30
router_id LVS_DEVELBACKUP # 在/etc/hosts 配置 127.0.0.1 `LVS_DEVELBACKUP 这行代码
}

vrrp_script chk_http_port {
script “/usr/local/src/nginx_check.sh” #检查脚本路径

interval 2   # 检查脚本时间间隔

weight 2

}

vrrp_instance VI_1 {
state MASTER #如果是备份服务器,将 MASTER 改为 BACKUP
interface eth0 # 网卡
virtual_router_id 51 #主、备机的virtual_router_id 必须相同
priority 100 # 主、备机取值不同的优先级,主机值交大,备份机值较小
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
192.168.200.16 # VRRP H虚拟地址
}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值