vlambda博客
学习文章列表

Nginx(二)反向代理和负载均衡实战

一、配置文件简介

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

#pid logs/nginx.pid;


events {
worker_connections 1024;
}


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

#charset koi8-r;

#access_log logs/host.access.log main;

location / {
root html;
proxy_pass http://192.168.43.243:8080;
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;
# }
#}

}

1. 全局块

从配置文件开始到 events 块之间的内容,主要会设置一些影响nginx 服务器整体运行的配置指令,主要包括配 置运行 Nginx 服务器的用户(组)、允许生成的 worker process 数,进程 PID 存放路径、日志存放路径和类型以 及配置文件的引入等。

  1. 定义nginx的运行的用户和用户组
user www www;
  1. 设置worker个数
worker_processes 1;

建议和CPU核数相同,一个worker占用一个进程。

  1. 全局日志类型定义, [ debug | info | notice | warn | error | crit ]
error_log /var/log/nginx/error.log info;
  1. 指定进程pid文件存放路径
pid /var/run/nginx.pid;
  1. 一个nginx进程打开的最多文件描述符数目,理论值应该是最多打开文件数(系统的值ulimit -n)与nginx进程数相除,但是nginx分配请求并不均匀,所以建议与ulimit -n的值保持一致
worker_rlimit_nofile 8192;

2. event块

events 块涉及的指令主要影响 Nginx 服务器与用户的网络连接,常用的设置包括是否开启对多 work process 下的网络连接进行序列化,是否允许同时接收多个网络连接,选取哪种事件驱动模型来处理连接请求,每个 word process 可以同时支持的最大连接数等。

  1. 参考事件模型,use [ kqueue | rtsig | epoll | /dev/poll | select | poll ];
use epoll;

epoll模型是Linux 2.6以上版本内核中的高性能网络I/O模型,如果跑在FreeBSD上面,就用kqueue模型。

  1. 单个进程最大连接数(最大连接数=连接数*进程数)
worker_connections 1024;

3. http块

这算是 Nginx 服务器配置中最频繁的部分,代理、缓存和日志定义等绝大多数功能和第三方模块的配置都在这里。

需要注意的是:http 块也可以包括 http全局块、server 块。

  1. http全局块

http全局块配置的指令包括文件引入、MIME-TYPE 定义、日志自定义、连接超时时间、单链接请求数上限等。

include mime.types; #文件扩展名与文件类型映射表
default_type application/octet-stream; #默认文件类型
#charset utf-8; #默认编码
server_names_hash_bucket_size 128; #服务器名字的hash表大小
client_header_buffer_size 32k; #上传文件大小限制
large_client_header_buffers 4 64k; #设定请求缓
client_max_body_size 8m; #设定请求缓
sendfile on; #开启高效文件传输模式,sendfile指令指定nginx是否调用sendfile函数来输出文件,对于普通应用设为 on,如果用来进行下载等应用磁盘IO重负载应用,可设置为off,以平衡磁盘与网络I/O处理速度,降低系统的负载。注意:如果图片显示不正常把这个改成off。
autoindex on; #开启目录列表访问,开启自动匹配合适下载服务器,默认关闭。
tcp_nopush on; #防止网络阻塞
tcp_nodelay on; #防止网络阻塞
keepalive_timeout 120; #长连接超时时间,单位是秒


#FastCGI相关参数是为了改善网站的性能:减少资源占用,提高访问速度。下面参数看字面意思都能理解。
fastcgi_connect_timeout 300;
fastcgi_send_timeout 300;
fastcgi_read_timeout 300;
fastcgi_buffer_size 64k;
fastcgi_buffers 4 64k;
fastcgi_busy_buffers_size 128k;
fastcgi_temp_file_write_size 128k;


#gzip模块设置
gzip on; #开启gzip压缩输出
gzip_min_length 1k; #最小压缩文件大小
gzip_buffers 4 16k; #压缩缓冲区
gzip_http_version 1.0; #压缩版本(默认1.1,前端如果是squid2.5请使用1.0)
gzip_comp_level 2; #压缩等级
gzip_types text/plain application/x-javascript text/css application/xml;
#压缩类型,默认就已经包含text/html,所以下面就不用再写了,写上去也不会有问题,但是会有一个warn。
gzip_vary on;
#limit_zone crawler $binary_remote_addr 10m; #开启限制IP连接数的时候需要使用


upstream blog.ha97.com {
    #upstream的负载均衡,weight是权重,可以根据机器配置定义权重。weigth参数表示权值,权值越高被分配到的几率越大。
    server 192.168.80.121:80 weight=3;
    server 192.168.80.122:80 weight=2;
    server 192.168.80.123:80 weight=3;
}
#日志格式设定
log_format access ‘$remote_addr – $remote_user [$time_local] “$request” ‘
$status $body_bytes_sent “$http_referer” ‘
‘”$http_user_agent” $http_x_forwarded_for’;
#定义本虚拟主机的访问日志
access_log /var/log/nginx/ha97access.log access;


  1. server块

这块和虚拟主机有密切关系,虚拟主机从用户角度看,和一台独立的硬件主机是完全一样的,该技术的产生是为了 节省互联网服务器硬件成本。每个 http 块可以包括多个 server 块,而每个 server 块就相当于一个虚拟主机。而每个 server 块也分为全局 server 块,以及可以同时包含多个 locaton 块。

  • 2.1 server全局块

最常见的配置是本虚拟机主机的监听配置和本虚拟主机的名称或IP配置。

listen        80; #监听端口
server_name   one.example.com  www.one.example.com; #域名,可以有多个,可以用空格隔开

access_log   /var/log/nginx.access_log  main; #访问日志
root         html;
  • 2.2 location块
#图片缓存时间设置
location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$
{
    expires 10d;
}
#JS和CSS缓存时间设置
location ~ .*\.(js|css)?$
{
    expires 1h;
}

#对 “/” 启用反向代理
location / {
proxy_pass http://127.0.0.1:88;
proxy_redirect off;
proxy_set_header X-Real-IP $remote_addr;
#后端的Web服务器可以通过X-Forwarded-For获取用户真实IP
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
#以下是一些反向代理的配置,可选。
proxy_set_header Host $host;
client_max_body_size 10m; #允许客户端请求的最大单文件字节数
client_body_buffer_size 128k; #缓冲区代理缓冲用户端请求的最大字节数,
proxy_connect_timeout 90; #nginx跟后端服务器连接超时时间(代理连接超时)
proxy_send_timeout 90; #后端服务器数据回传时间(代理发送超时)
proxy_read_timeout 90; #连接成功后,后端服务器响应时间(代理接收超时)
proxy_buffer_size 4k; #设置代理服务器(nginx)保存用户头信息的缓冲区大小
proxy_buffers 4 32k; #proxy_buffers缓冲区,网页平均在32k以下的设置
proxy_busy_buffers_size 64k; #高负荷下缓冲大小(proxy_buffers*2)
proxy_temp_file_write_size 64k;
#设定缓存文件夹大小,大于这个值,将从upstream服务器传
}


#设定查看Nginx状态的地址
location /NginxStatus {
stub_status on;
access_log on;
auth_basic “NginxStatus”;
auth_basic_user_file conf/htpasswd;
#htpasswd文件的内容可以用apache提供的htpasswd工具来产生。
}



#本地动静分离反向代理配置
#所有jsp的页面均交由tomcat或resin处理
location ~ .(jsp|jspx|do)?$ {
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://127.0.0.1:8080;
}
#所有静态文件由nginx直接读取不经过tomcat或resin
location ~ .*.(htm|html|gif|jpg|jpeg|png|bmp|swf|ioc|rar|zip|txt|flv|mid|doc|ppt|pdf|xls|mp3|wma)$
{ expires 15d; }
location ~ .*.(js|css)?$
{ expires 1h; }

二、反向代理配置

  1. 安装Nginx:请参考Nginx(一)介绍和安装
  2. 修改windows主机hosts文件,在文件中添加如下一条:
# ip            域名
192.168.43.243 www.javacfox.com
server {
        # 1. 添加监听端口
        listen       80;
        # 2. 添加监听主机
        server_name  192.168.43.243;


        location / {
            root   html;
            # 3. 添加代理地址 
            proxy_pass http://192.168.43.243:8080;
            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;
        }

    }

  1. 启动tomcat
[root@localhost nginx]# docker ps -a
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS                      PORTS                               NAMES
172325cae7ec        nginx               "/docker-entrypoin..."   28 hours ago        Up About an hour            0.0.0.0:80->80/tcp                  nginx
d4006ce6030e        mysql               "docker-entrypoint..."   6 days ago          Exited (255) 34 hours ago   0.0.0.0:3306->3306/tcp, 33060/tcp   mysql
df82919b5d9e        tomcat              "catalina.sh run"        6 days ago          Up 9 hours                  0.0.0.0:8080->8080/tcp              tomcat
[root@localhost nginx]# docker start tomcat
tomcat
  1. 重启nginx
[root@localhost nginx]# docker restart nginx
nginx

  1. 测试,如果直接访问 http://www.javacfox.com成功,说明配置成功
image

三、负载均衡配置

  1. 启动两个tomcat,在其中一个webapps中添加test/index.html(里面内容为:test:8080,success!!!),另外一个tomcat不添加,采用轮询的时候,一次可以访问成功,一次返回404

  2. 启动两个tomcat

  3. 修改nginx.comf的配置

    # 1. 配置访问的服务器:轮询(默认),weight(权重),http_hash(同一ip访问同一服务,解决了分布式全局token问题),fair(按照响应速度)
    upstream javacfox.com {
     server 192.168.43.243:8080;
     server 192.168.43.243:8081;
    }

    server {
        listen       80;
        server_name  192.168.43.243;

        location / {
            root   html;
            # 将代理地址改为javacfox.com
   proxy_pass http://javacfox.com;
            index  index.html index.htm;
        }

        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

    }
  1. 重启nginx: docker restart nginx
  2. 测试
第一次访问
第二次访问返回404

从测试结果来看,第一次返回访问结果,第二次返回404,和预测结果一致,说明负载均衡配置成功。