Nginx概要 和 Nginx -keepalived 配置

初步认识

Nginx 是什么

nginx是一个高性能的反向代理服务器

正向代理:代理的是客户端

反向代理:代理的是服务端

Apache 、Tomcat、Nginx

Apache 、Nginx 是静态资源服务器

Tomcat 是动态资源服务器 【jsp/servlet】

作用

请求分发

负载均衡

反向代理

Nginx 安装

cd /guaoran/installPack
wget http://nginx.org/download/nginx-1.14.2.tar.gz
tar  -zxvf nginx-1.14.2.tar.gz 
-- 安装依赖
yum install pcre-devel
yum install zlib-devel

-- 安装到指定目录
cd nginx-1.14.2
./configure --prefix=/guaoran/nginx
make && make install

启动和停止在

-- 到安装目录,运行
cd /guaoran/nginx/sbin/
./nginx
-- 停止
./nginx -s stop

Nginx 配置

conf/nginx.conf

http
虚拟主机配置
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;
        }
}
基于端口号的虚拟主机
server {
    listen 8080;
    server_name localhost;
    location / {
        root html;
        index index.html;
    }
}

192.168.45.135:8080

基于域名的虚拟主机

www.guaoran.cn / login.guaoran.cn /congcong.guaoran.cn /

server {
    listen 80;
    server_name www.guaoran.cn;
    location / {
        root html;
        index index.html;
    }
}
server {
    listen 80;
    server_name congcong.guaoran.cn;
    location / {
        root html;
        index congcong.html;
    }
}
server {
    listen 80;
    server_name login.guaoran.cn;
    location / {
        root html;
        index login.html;
    }
}

找到 C:\Windows\System32\drivers\etc\hosts 文件

在本地配置域名映射,

192.168.45.135 login.guaoran.cn

192.168.45.135 congcong.guaoran.cn

192.168.45.135 www.guaoran.cn

cd /guaoran/nginx/html 目录中

创建 login.html、congcong.html

访问 congcong.guaoran.cn 、login.guaoran.cn 、www.guaoran.cn 可看到效果

location
配置语法

location [= | ~* | ^~ ] /uri/ {…}

配置规则

location = /uri 精准匹配
location ^~ /uri 前缀匹配
location ~ /uri
location / 通用匹配

规则的优先级
1 location = /
2 location = /index
3 location ^~ /article/
4 location ^~ /article/files/
5 location ~ \.(gif|png|js|css)$
6 location /
http://192.168.45.135/ ->1
http://192.168.45.135/index ->2
http://192.168.45.135/article/files/1.txt ->4
http://192.168.45.135/git.png ->5
  • 精准匹配是优先级最高
  • 普通匹配(最长的匹配)
  • 正则匹配
实际使用建议
location =/ {
}
location / {
}
location ~* \.(gif|....)${
}
Nginx模块
模块分类

核心模块 ngx_http_core_module

标准模块 http模块

实现基于ip的访问控制功能
1、allow address | CIDR | unix: | all; 允许ip或其他、全部访问
2、deny address | CIDR | unix: | all; 不允许访问
自上而下检查,一旦匹配,将生效,条件严格的置前

第三方模块

添加第三方模块

原来所安装的配置,你必在重新安装新模块的时候加上,不能直接make install

-- 进入到nginx 安装的目录 
cd /guaoran/nginx/sbin
-- 查看安装时带的参数
./nginx -V 
-- 会有这种信息,就是你安装时带的参数   [configure arguments: --prefix=/guaoran/nginx]
-- 进入到解压nginx的目录里
cd /guaoran/installPack/nginx-1.14.2
-- 再次执行安装
./configure --prefix=/guaoran/nginx --with-http_stub_status_module --with-http_random_index_module
-- 执行make,不要make install,否则就是重新安装了
make 
--将执行后的nginx 文件复制到安装,目录中
cp -r objs/nginx /guaoran/nginx/sbin/
-- 启动nginx
/guaoran/nginx/sbin/nginx

http_stub_status_module:状态模块

location /status {
	stub_status;
}

http_random_index_module:随机显示主页模块

完整的配置文件

server {
    listen 80;
    server_name www.guaoran.cn;
    location / {
    	root html;
    	random_index on;
    	index index.html;
    }
    location /status {
    	stub_status;
    }
}

Nginx 实践

192.168.45.131 192.168.45.134 启动两个Tomcat 8080端口

修改nginx.conf 文件,使用外部的配置server端的文件

http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;
    ## 使用外部的配置:./extra/
    include extra/*.conf;    
}

反向代理

extra/proxy_demo.conf;

server {
    listen 80;
    server_name localhost;
    location / {
        proxy_pass http://192.168.45.131:8080;
        ## 获得客户端的ip地址,如果用nginx,会显示nginx的ip地址
        proxy_set_header Host $host;
        ## 获得客户端的真实ip地址
        proxy_set_header X-Real-IP $remote_addr;
        ## 获得整个的代理过程的ip地址
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        ## 当向一台服务器转发请求出现错误时,继续换一台服务器来处理这个请求。
        proxy_next_upstream error timeout http_500 http_503;
        ## 代理连接超时时间
        proxy_connect_timeout 60s;
        ## 发送数据超时时间
        proxy_send_timeout 60s;
        ## 获得数据超时时间
        proxy_read_timeout 60s;
        ## 用来解决跨域,设置为 * 表示该资源谁都可以用
        add_header 'Access-Control-Allow-Origin' '*';
        ## 允许的方法请求类型
        add_header 'Access-Control-Allow-Methods' 'GET,POST,DELETE';
        ## 允许的请求头类型是任意的
        add_header 'Aceess-Control-Allow-Header' 'Content-Type,*';
    }
}

负载均衡

extra/lb_demo.conf;

upstream

语法: server address [paramters]

负载均衡策略算法

  • 轮询算法(默认), 如果后端服务器宕机以后,会自动踢出

    • 配置:

      upstream backend_default  {
        server   192.168.45.131:8080 ;
        ## 如果失败两次,则等待10s在进行轮询该台服务器
        server   192.168.45.134:8080 max_fails=2 fail_timeout=10s;
      }
      
      server {
        location / {
          proxy_pass  http://backend_default;
        }
      }
      176
      
  • ip_hash 根据请求的ip地址进行hash

    • 配置:

      upstream backend_ip_hash {
        ## 指定ip_hash 策略
        ip_hash;
        server   192.168.45.131:8080;
        server   192.168.45.134:8080;
      }
      server {
        location / {
          proxy_pass  http://backend_ip_hash;
        }
      }
      
      
    • 应用场景:

      • 可以做单点登录,不过如果该台服务器重启,则会重新登录
  • 权重轮询

    • 配置:

      upstream backend_weight  {
        ## 指定权重
        server   192.168.45.131:8080 weight=1 ;
        server   192.168.45.134:8080 weight=2;
      }
      server {
        location / {
          proxy_pass  http://backend_weight;
        }
      }
      
      

Nginx 动静分离

静态资源文件类型

nginx/conf/mime.types

配置

cat load_balance_demo.conf

upstream tomcat  {
  server   192.168.45.131:8080;
  server   192.168.45.134:8080;
}
server {
        listen 80;
        server_name localhost;
        location / {
            proxy_pass http://tomcat;
        }
        ## 做动静分离
        location ~ .*\.(js|css|png|svg|ico|jpg)$ {
            root static-resource;
            ## 指定缓存过期时间 1天  expires 30s|m|h|d
            expires 1d;
        }
}

在/guaoran/nginx/ 目录下创建static-demo 目录,并将Tomcat的静态资源文件放到里面,

这样访问静态文件的时候,就可以去访问static-resource 目录中的文件了

如果是403的话,可以检查下,static-resource的读权限是否存在

压缩 Gzip

我们一个网站一定会包含很多的静态文件,比如图片、脚本、样式等等,而这些css/js可能本身会比较大,那么在网络传输的时候就会比较慢,从而导致网站的渲染速度。因此Nginx中提供了一种Gzip的压缩优化手段,可以对后端的文件进行压缩传输,压缩以后的好处在于能够降低文件的大小来提高传输效率 .

访问Tomcat 静态资源文件访问

在这里插入图片描述

进行配置压缩:

cd /guaoran/nginx
vim conf/nginx.conf

配置如下:

http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;
    ## 使用外部的配置:./extra/
    include extra/*.conf;    
    
    ## 开启gzip压缩
    gzip on;
    ## 开始压缩的最小长度(小于多少就不做压缩),可以指定单位,比如 5k
    gzip_min_length 5k;
    ## 压缩级别[1-9], 级别越高,压缩越小,但是会占用CPU资源
    gzip_comp_level 3;
    ## 对那些类型的文件做压缩 (conf/mime.conf)
    gzip_types application/javascript image/jpeg image/svg+xml;
    ## 设置gzip申请内存的大小,作用是按指定大小的倍数申请内存空间。即以32k为单位的4倍申请内存。
    gzip_buffers 4 32k;
    ## 是否传输gzip压缩标识; 启用应答头"Vary: Accept-Encoding";
    gzip_vary on;
}

重新加载

./nginx/sbin/nginx -s reload

清除缓存再次访问:

在这里插入图片描述

能看到大小是一样的,但是传输列明显发生了变化。

防盗链

类似微信的图片在微信外有的显示不出来

一个网站上会有很多的图片,如果你不希望其他网站直接用你的图片地址访问自己的图片,或者希望对图片有版权保护。再或者不希望被第三方调用造成服务器的负载以及消耗比较多的流量问题,那么防盗链就是你必须要做的

 ## 做动静分离
 location ~ .*\.(js|css|png|svg|ico|jpg)$ {
 	## 防盗链,只有135 和 www.guaoran.cn 才能访问这些资源,否则返回404
 	valid_referers none blocked 192.168.45.135 www.guaoran.cn;
    if ($invalid_referer) {
    	return 404;
    }
 	root static-resource;
 }

Nginx 扩展

多路复用

worker_processes 工作进程数,可以设置为CPU的核心数

keepalived

Keepalived是Linux下一个轻量级别的高可用解决方案,Keepalived软件起初是专为LVS负载均衡软件设计的,用来管理并监控LVS集群系统中各个服务节点的状态,后来又加入了可以实现高可用的VRRP功能。因此,Keepalived除了能够管理LVS软件外,还可以作为其他服务(例如:Nginx、Haproxy、MySQL等)的高可用解决方案软件

安装

需要在两台服务器上安装keepalived 和 nginx [in 192.168.45.135,192.168.45.134]

cd /guaoran/installPack/
wget http://www.keepalived.org/software/keepalived-2.0.7.tar.gz
tar -zxvf keepalived-2.0.7.tar.gz 
mkdir /guaoran/keepalived
cd keepalived-2.0.7/
-- 添加依赖
yum install openssl-devel
-- 安装
./configure --prefix=/guaoran/keepalived --sysconf=/etc
make && make install
cd  /guaoran/keepalived/
-- 创建软连接
ln -s sbin/keepalived /sbin
-- 放到系统服务里
cp /guaoran/installPack/keepalived-2.0.7/keepalived/etc/init.d/keepalived /etc/init.d
chkconfig --add keepalived
chkconfig keepalived on
service keepalived start
-- 查看是否启动
service keepalived status

keepalived的配置

192.168.45.135 作为 master

192.168.45.134 作为 backup

192.168.45.100 作为虚拟ip,不存在的

in master

vi /etc/keepalived/keepalived.conf

! Configuration File for keepalived

global_defs { 
	##  运行keepalived服务器的标识,在一个网络内应该是唯一的 
	router_id LVS_DEVEL
	enable_script_security
} 
## 监听nginx的服务,
vrrp_script chk_nginx_service {
    script "/guaoran/nginx/sbin/nginx-ha-check.sh"
    interval 3
    weight -10
    user root
}
## vrrp实例定义部分
vrrp_instance VI_1 {
	## 设置lvs的状态,MASTER和BACKUP两种,必须大写
	state MASTER  
	## 设置对外服务的接口
	interface ens33 
	## 设置虚拟路由标示,这个标示是一个数字,同一个vrrp实例使用唯一标示
	virtual_router_id 51  
	## 定义优先级,数字越大优先级越高,在一个vrrp_instance下,master的优先级必须大于backup
	priority 100  
	## 设定master与backup负载均衡器之间同步检查的时间间隔,单位是秒
	advert_int 1  
	## 设置验证类型和密码
	authentication {
		auth_type PASS 
		## 验证密码,同一个vrrp_instance下MASTER和BACKUP密码必须相同
		auth_pass 1111  
	} 
	## 设置虚拟ip地址,可以设置多个,每行一个
	virtual_ipaddress {  
		192.168.45.100 
	} 
	## 执行监控的服务
	track_script {
        chk_nginx_service
	}
} 
## 设置虚拟服务器,需要指定虚拟ip和服务端口 
virtual_server 192.168.45.100 80 { 
	## 健康检查时间间隔
	delay_loop 6 
	## 负载均衡调度算法 
	lb_algo rr 
	## 负载均衡转发规则 
	lb_kind NAT 
	## 设置会话保持时间 
	persistence_timeout 50 
	## 指定转发协议类型,有TCP和UDP两种 
	protocol TCP 
	## 配置服务器节点1,需要指定real server的真实IP地址和端口 
	real_server 192.168.45.135 80 { 
         ## 设置权重,数字越大权重越高
		weight 1
		## realserver的状态监测设置部分单位秒 
         CP_CHECK {  
            ## 超时时间45
            connect_timeout 3 
            ## 间隔 
            delay_before_retry 3 
            ## 端口 
            connect_port 80 
		} 
	} 
}

in backup

vi /etc/keepalived/keepalived.conf

! Configuration File for keepalived

global_defs { 
	##  运行keepalived服务器的标识,在一个网络内应该是唯一的 
	router_id LVS_DEVEL
} 
## vrrp实例定义部分
vrrp_instance VI_1 {
	## 设置lvs的状态,MASTER和BACKUP两种,必须大写
	state BACKUP  
	## 设置对外服务的接口
	interface ens33 
	## 设置虚拟路由标示,这个标示是一个数字,同一个vrrp实例使用唯一标示
	virtual_router_id 51  
	## 定义优先级,数字越大优先级越高,在一个vrrp_instance下,master的优先级必须大于backup
	priority 50  
	## 设定master与backup负载均衡器之间同步检查的时间间隔,单位是秒
	advert_int 1  
	## 设置验证类型和密码
	authentication {
		auth_type PASS 
		## 验证密码,同一个vrrp_instance下MASTER和BACKUP密码必须相同
		auth_pass 1111  
	} 
	## 设置虚拟ip地址,可以设置多个,每行一个
	virtual_ipaddress {  
		192.168.45.100 
	} 
} 
## 设置虚拟服务器,需要指定虚拟ip和服务端口 
virtual_server 192.168.45.100 80 { 
	## 健康检查时间间隔
	delay_loop 6 
	## 负载均衡调度算法 
	lb_algo rr 
	## 负载均衡转发规则 
	lb_kind NAT 
	## 设置会话保持时间 
	persistence_timeout 50 
	## 指定转发协议类型,有TCP和UDP两种 
	protocol TCP 
	## 配置服务器节点1,需要指定real server的真实IP地址和端口 
	real_server 192.168.45.134 80 { 
         ## 设置权重,数字越大权重越高
		weight 1
		## realserver的状态监测设置部分单位秒 
         CP_CHECK {  
            ## 超时时间45
            connect_timeout 3 
            ## 间隔 
            delay_before_retry 3 
            ## 端口 
            connect_port 80 
		} 
	} 
}

重新启动 keepalived

service keepalived restart

通过脚本实现动态切换 [由于只有一个backup,所以监听服务的脚本只在135 master上加了。]

cd /guaoran/nginx/sbin

vim nginx-ha-check.sh

查看nginx是否启动,如果未启动则关闭keepalived服务,这样当 master keepalived 的 nginx挂了之后,就可以实现nginx的切换

#!/bin/sh
A=`ps -C nginx --no-header |wc -l` 
if [ $A -eq 0 ] 
	then 
		echo 'nginx server is died' 
		service keepalived stop 
fi

配置nginx的监听ip端口

分别在192.168.45.135,192.168.45.134 启动一个Tomcat 进行监听,在134的Tomcat中把css去掉,这样的话,当nginx master挂掉之后,nginx backup启动后就会看出来效果

访问:http://192.168.45.100 会发现一直访问135的nginx, 当把135的nginx关闭之后,再次刷新页面 ,会发现在访问134 backup的nginx

Openresty

OpenResty是一个通过Lua扩展Nginx实现的可伸缩的Web平台,内部集成了大量精良的 Lua 库、第三方模块以及大多数的依赖项。用于方便地搭建能够处理超高并发、扩展性极高的动态 Web 应用、Web 服务和动态网关。

安装

下载目录:http://openresty.org/cn/download.html

  • 通过官方预编译安装包安装
    • http://openresty.org/cn/linux-packages.html
    • 一步一步执行命令即可,安装后,在/usr/local/openresty 中
  • 通过源文件安装,跟nginx差不多,就是基于nginx做的扩展:
    • https://openresty.org/download/openresty-1.13.6.2.tar.gz

Nginx 官网配置

常用配置

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值