nginx安装使用代理负载均衡缓存

473 阅读5分钟

本文已参加「新人创作礼」活动,一起开启掘金创作之路

最近学习redis分布式锁中使用nginx做负载均衡使用上遇到很多问题,虽然有发过手写笔记,但使用上不是很好,这次再来总结复习一下

介绍

  1. 为什么使用nginx
    • tomcat是我们经常使用的web容器,也很稳定,但是在应对高并发的场景下,tomcat会消耗大量的内存,因为用户的一个请求对应的是tomcat的一个线程,而对于nginx不同nginx的一个线程可以处理用户的几个请求大大降低了内存的使用,一般使用nginx做反向代理多个tomcat配合负载均衡

安装

  1. 安装基础依赖yum -y install make zlib zlib-devel gcc-c++ libtool openssl openssl-devel pcre pcre-devel vim wget
  2. 下载nginx wget https://nginx.org/download/nginx-1.18.0.tar.gz
  3. 解压缩tar -zxvf nginx-1.18.0.tar.gz && cd nginx-1.18.0
  4. 配置编译安装./configure && make && make install
  5. 模块更新添加状态监听模块 ./configure --with-http_stub_status_module && make && make install
  6. 复制命令cp sbin/nginx /usr/bin/

操作命令

  1. 帮助nginx -?
  2. 默认启动nginx
  3. 指定 nginx -c /tmp/nginx.conf
  4. 指定nginx程序目录nginx -p /usr/local/nginx/
  5. 快速停止nginx -s stop
  6. 优雅停止nginx -s quit
  7. 热部署nginx -s reload
  8. 重新打开日志文件nginx -s reopen
  9. 设置全局命令 如设置启动用户为rootnginx -g "user root"

nginx配置

  1. listen 端口号
    • listen 80;
    • server_name ip或域名 支持正则
    • server_name 127.0.0.1
  2. location 支持正则
    • location [=,,,*,^~|@]/uri,
      1. = 表示把uri作为字符串精准匹配
      2. / 基于uri目录匹配
      3. ~ 表示正则匹配uri时大小写敏感
      4. ~* 表示正则匹配uri时忽略大小写
      5. ^~ 表示正则匹配大小写时只取前半部分uri
      6. 匹配优先规则
        1. 精准匹配
        2. 正则匹配
        3. 前缀最大匹配
        4. 配置靠前
  3. root指定站点根目录
  4. alias 指定站点别名 移除uri 基于alias路径寻找文件

动静分离

  1. 基于目录的动静分离
    server {
        listen 80;
        server_name *.luban.com;
        root /usr/www/luban;
    location / {
        index luban.html;
     }
location /static {
       alias /usr/www/static;
    }
}
  1. 基于正则表达式的动静分离
location ~* \.(gif|jpg|png|css|js)$ {
    root /usr/www/static;
}
  1. 防盗链
valid_referers none blocked *.baidu.com
    if($invalid_referer){
        return 403;
    }
  1. 下载限速
    location /download{
        limit_rate 1m;   限速1mbps
        limit_rate_after 30m;超过30m之后启动限速
    }
    
  2. 创建ip黑名单 (lcoation下)
    echo 'deny 192.168.150.1;' >> block.ip
    封禁指定ip
    deny 192.168.150.1;
    允许指定ip
    allow 192.168.150.2;
    开放指定ip段
    allow 192.168.150.0/24
    封禁所有
    deny all
    开放所有
    allow all
    创建黑名单文件
    include ../block.ip'
    

日志配置

  1. 日志格式
    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;
    #基于域名打印日志
    access_log logs/$host.access.log main;
    
  2. erro日志配置
    erro_log/path/file level
    level是日志的输出级别,取值范围是debug、info、notice、warn、error、crit、alert、emerg,
    erro_log/logs/erro.log error
    
  3. 针对指定客户端输出debug日志(需安装debug模块 -with-debug)
    events{
    debug_connection 192.168.0.147
    debug_connection 192.168.150.0/24
    }
    

正向代理与反向代理

  1. 正向代理 服务端不知道真正请求的客户端 主要作用为屏蔽客户端ip,集中式缓存,解决客户端不能直连的问题,应用为翻墙,爬虫,maven代理,客户端使用的代理
  2. 反向代理 客户端不知道真正返回数据的服务器主要作用屏蔽服务器内部实现,负载均衡,缓存,应用为nginx,apache负载均衡,服务器使用的代理
  3. 配置
    正向代理
    location =/baidu.html{
    proxy_pass http://www.baidu.com
    }
    反向代理
    location /test{
    proxy_pass 127.0.0.1:8080 
    }
    
  4. 代理相关参数
proxy_pass   代理服务
proxy_redirect off 是否运行重定向
proxy_set_header Host $host  将header传入后端服务
proxy_set header X-Forwarded-For $remote_addr 设置请求头即客户端ip
proxy_connect_time 90 连接代理服务超时时间
proxy_read_timeout 90 读取最大时间
proxy_buffer_size 4k/8k  nginx使用该大小去请求内存,等同于指定了header的最大长度
proxy_buffers 256 8k 请求 请求body的大小,当前buffer不够存储时会申请一个最多256个
proxy_busy_buffers_size 64k   busy状态下buffer有多大,nginx在没有完全读完后端响应就开始向客户端传输数据,读满返回或读完返回
proxy_temp_file_write_size  一次能写入的临时文件的大小

负载均衡

upstream backend {     
	server 127.0.0.1:8010 weight=1;
	server 127.0.0.1:8080 weight=2;
	server 127.0.0.1:8030 weight=1 backup;
}
location / {
	proxy_pass http://backend;
}
  1. upstream参数配置
    • server 反向代理地址与参数
    • weight 权重
    • max_fails 失败多少次认为主机挂了踢出
    • fail_timeout 踢出后重新探测时间
    • max_conns 允许最大连接数
    • slow_start 当节点恢复,不立即加入而是等待slow_start 后加入服务队列
  2. 负载均衡算法
    • weight 轮询权重
    • ip_hash 基于hash计算,保证session一致性
    • url_hash 静态资源缓存,节约存储 加快速度 图片服务每个服务器都存储浪费资源
    • least_conn 最小连接
    • least_time最小响应时间 计算平均响应时间然后取响应最快的那个

高速缓存

proxy_cache_path 指定缓存路径
levels 为目录级别 nginx会将路径进行md5加密   levels=1:2 指取md5后的数据倒数1位/倒数2位/作为目录 
keys_zone 名称 内存大小
inactive 20天内没有人访问这个链接了自动删除
max_size 最大占用硬盘1g
proxy_cache_path /data/nginx/cache_jamin levels=1:2 keys_zone=cache_jamin:500m inactive=20d max_size=1g;
proxy_cache cache_jamin  缓存名称
proxy_cache_key $host$uri$is_args$args   将全路径进行md5作为key
proxy_cache_valid 200 304 12h;   对于200304状态码缓存过期时间为12小时,过期后请求后端服务器
删除缓存
wget http://labs.frickle.com/files/ngx_cache_purge-2.3.tar.gz   下载模块包并解压
./configure --prefix=/root/svr/nginx --with-http_stub_status_module --with-http_ssl_module  --add-module=/root/ngx_cache_purge-2.3    指定安装目录
make 编译
cp /root/nginx1.8.0/objs/nginx   /usr/local/nginx/    替换文件

location ~ /clear(/.*) {
  #允许访问的IP
   allow           127.0.0.1;
   allow           192.168.150.1;
   #禁止访问的IP
   deny            all;
   #配置清除指定缓存区和路径(与proxy_cache_key一至)
   proxy_cache_purge    cache_jamin $host$1$is_args$args;
}  

请求地址http://192.168.150.110/?a=1生成缓存文件
清除缓存http://www.luban.com/clear/?a=1

参数调优

  1. worker_processes numberwork的线程数量 如果不会出现阻塞式的调用一半多少个cpu配置多少个work线程
  2. worker_connections number 每个worker进程的最大连接数
  3. worker_cpu_affinity cpumask....配置work线程绑定cpu
  4. worker_priority nicework线程的优先级
  5. worker_rlimit_nofilework线程可以打开的文件数
  6. accept_mutex on 打开或关闭负载均衡锁
  7. accept_mutex_delayworker线程在获取不到accept锁后重新尝试时间