Nginx实现反向代理负载均衡与静态缓存
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Nginx实现反向代理负载均衡与静态缓存相关的知识,希望对你有一定的参考价值。
介绍:
nginx是一款轻量级的Web服务器/反向代理服务器及电子邮件(IMAP/POP3)代理服务器。在连接高并发的情况下,Nginx是Apache服务器不错的替代品,能够支持高达50000个并发连接数的响应。
实验环境:
Hostname | IP | 系统 | 规划 |
n2.preferred | 192.168.1.2 | Centos 6.5 | Web server |
n3.preferred | 192.168.1.3 | Centos 6.5 | Web server |
n6.preferred | 192.168.1.6 | Centos 7.0 | Nginx proxy |
实验拓扑:
利用Nginx代理对Client访问后端Web服务器的请求提供负载均衡
实验步骤:
一、安装:(我们在这里使用编译安装)
[[email protected] ~]#yum install groupinstall "Development Tools" "Server Platform Development" <---安装依赖包组 [[email protected] ~]#yum install pcre-devel openssl-devel zlib-devel -y <---安装相应软件 [[email protected] ~]# tar -xf nginx-1.6.1.tar.gz [[email protected] ~]# cd nginx-1.6.1/ [[email protected] nginx-1.6.1]# ls auto CHANGES CHANGES.ru conf configure contrib html LICENSE man README src [[email protected] nginx-1.6.1]# ./configure --prefix=/usr/local/nginx --conf-path=/etc/nginx/nginx.conf --user=nginx --group=nginx --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --pid-path=/var/run/nginx/nginx.pid --lock-path=/var/lock/nginx.lock --with-http_ssl_module --with-http_stub_status_module --with-http_gzip_static_module --with-http_flv_module --with-http_mp4_module --http-client-body-temp-path=/var/tmp/nginx/client --http-proxy-temp-path=/var/tmp/nginx/proxy --http-fastcgi-temp-path=/var/tmp/nginx/fastcgi <---各参数请参照官方文档 ... 过程省略 [[email protected] nginx-1.6.1]# make && make install ... 过程省略 [[email protected] ~]# groupadd -r nginx <---创建用户 [[email protected] ~]# useradd -r -g nginx nginx <---创建用户 [[email protected] ~]# mkdir /var/tmp/nginx/{client,proxy,fastcgi} -p <---创建编译安装时所需的目录 [[email protected] ~]# cd /etc/nginx/ [[email protected] nginx]# ls fastcgi.conf koi-utf nginx.conf uwsgi_params fastcgi.conf.default koi-win nginx.conf.default uwsgi_params.default fastcgi_params mime.types scgi_params win-utf fastcgi_params.default mime.types.default scgi_params.default #我们主要对nginx.conf这个文件进行配置
Nginx的主配置文件介绍:
Nginx的配置文件中参数较多,我主要说说重要的部分。
#user nobody; #运行用户 worker_processes 1; #启动进程,通常设置成cpu数量减1 #全局错误日志及Pid文件 #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; #单个后台worker process进程的最大并发链接数 } #设定http服务器,利用它的反向代理功能提供负载均衡支持 http { include mime.types; #设定mime类型,类型由mime.type文件定义 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; #指令指定 nginx 是否调用 sendfile 函数(zero copy 方式)来输出文件,对于普通应用必须设为 on,如果用来进行下载等应用磁盘IO重负载应用,可设置为 off,以平衡磁盘与网络I/O处理速度,降低系统的uptime sendfile on; #tcp_nopush on; #keepalive_timeout 0; #连接超时时间 keepalive_timeout 65; #gzip on; #开启gzip压缩 server { listen 80; #侦听80端口 server_name localhost; #定义使用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 # #PHP脚本请求全部转发到fastcgi处理,使用fastcgi默认配置 #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验证访问 # 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实现反向代理负载均衡
以下在n6.preferred服务器上实现
#定义一个upstream(负载均衡组),组名为n6_proxy,在server组里直接调用组名 http { ... upstream n6_proxy { server 192.168.1.2:80 weight=1 max_fails=2 fail_timeout=1; <---两台real server为WEB的IP server 192.168.1.3:80 weight=1 max_fails=2 fail_timeout=1; #权重为1,1秒算超时连续2次超时说明检测失败 } server { listen 80; server_name n6.preferred; <---修改为本机hostname #charset koi8-r; #access_log logs/host.access.log main; location / { root /var/www/html; index index.html index.htm; proxy_pass http://n6_proxy; <---将对本服务器首页的请求代理至负载均衡组n6_proxy的两台real server } } [[email protected] nginx]# /usr/local/nginx/sbin/nginx [[email protected] nginx]# ss -tunlp | grep :80 Netid State Recv-Q Send-Q Local Address:Port Peer Address:Port tcp LISTEN 0 128 *:80 *:* users:(("nginx",31418,6),("nginx",31417,6)) #nginx监听了80端口
将n2.preferred和n3.preferred两台web server安装httpd,并添加一个测试页面
#以下在n2.preferred上实现 [[email protected] ~]# yum install httpd -y [[email protected] ~]# echo ‘<h1> real web server is n2.preferred</h1>‘ > /var/www/html/index.html <---测试页面 #以下在n3.preferred上实现 [[email protected] ~]# yum install httpd -y [[email protected] ~]# echo ‘<h1> real web server is n3.preferred</h1>‘ > /var/www/html/index.html [[email protected] ~]# service httpd start; ssh [email protected] ‘service httpd start‘ <---同时启动httpd Starting httpd: httpd: Could not reliably determine the server‘s fully qualified domain name, using n3.preferred for ServerName [ OK ] Starting httpd: httpd: apr_sockaddr_info_get() failed for n2.preferred httpd: Could not reliably determine the server‘s fully qualified domain name, using 127.0.0.1 for ServerName [ OK ] [[email protected] ~]# ss -tunl | grep :::80; ssh [email protected] ‘ss -tunl | grep :::80‘ <---查看80端口是否都已侦听 tcp LISTEN 0 128 :::80 :::* The authenticity of host ‘192.168.1.2 (192.168.1.2)‘ can‘t be established. RSA key fingerprint is 24:93:80:46:ac:22:62:a9:6d:df:46:a1:94:a8:9a:77. tcp LISTEN 0 128 :::80 :::*
测试(负载均衡):
三、配置Nginx实现静态资源缓存
#创建缓存目录 [[email protected] ~]# mkdir /cache/nginx -p [[email protected] ~]# chown nginx:nginx /cache/nginx/ <---将属主和属组都该为nginx [[email protected] ~]# vim /etc/nginx/nginx.conf <---添加以下参数 http { ... #缓存路径,1:1表示1级目录下的子目录名称只能有1个字符,缓存key名称为mycache(在location中会调用),缓存大小为32M proxy_cache_path /cache/nginx/ levels=1:1 keys_zone=mycache:32m server { ... location /forum/ { proxy_cache mycache; #调用缓存key的mycache proxy_cache_vaild 200 1m; #返回值为200缓存1分钟 proxy_cache_vaild 301 302 10m; #返回值为301,302缓存10分钟 proxy_cache_vaild any 1m; #其它所有返回值都统统为1分钟 proxy_pass http://192.168.1.2/index.html; #将url为/forum/的代理至web(n2.preferred)上 proxy_set _header Host $host; #把客户端访问的真实主机名传递给后端Web服务器 proxy_set_header X-Real-IP $remote_addr; #把客户端访问的真实IP传递给后端Web服务器 } #要在客户端访问时记录真实的访问主机名与IP,则Web服务器上还需修改一项参数 [[email protected] ~]# vim /etc/httpd/conf/httpd.conf LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined <---将%h修改为{X-Real-IP}i两台Web服务器都需要修改 LogFormat "%{X-Real-IP}i %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
测试: #访问此url将只会被分配n2.preferred服务器上
[[email protected] nginx]# pwd /cache/nginx [[email protected] nginx]# ls <---生成了一个缓存文件 6 [[email protected] nginx]# cat 6/2/def821edf5c378c0eaa684572237a026 m X3l XLW KEY: http://192.168.1.2/index.html HTTP/1.1 200 OK Date: Thu, 22 Sep 2016 07:53:29 GMT Server: Apache/2.2.15 (CentOS) Last-Modified: Thu, 22 Sep 2016 01:27:52 GMT ETag: "60806-2a-53d0e920461cd" Accept-Ranges: bytes Content-Length: 42 Connection: close Content-Type: text/html; charset=UTF-8 <h1> real web server is n2.preferred</h1>
查看来自Client访问的IP地址
三、静态资源缓存对于服务器的提升
到这里我们的工作已经基本全部完成了,这时估计有人会问“我们做的这些,有什么用”?好~那我将用最后一项压力测试让你明白!为了达到真实测试目的,我将让Nginx服务器不再提供缓存。
#注释掉相应的缓存配置参数 http { ... # proxy_cache_path /cache/nginx/ levels=1:1 keys_zone=mycache:32m; upstream n6_proxy { server 192.168.1.2:80 weight=1 max_fails=2 fail_timeout=1; server 192.168.1.3:80 weight=1 max_fails=2 fail_timeout=1; } server { listen 80; server_name n6.preferred; #charset koi8-r; #access_log logs/host.access.log main; location / { root /usr/share/nginx/html; index index.html index.htm; proxy_pass http://n6_proxy/; #proxy_pass http://192.168.1.2/; } location /forum/ { # proxy_cache mycache; # proxy_cache_valid 200 1m; # proxy_cache_valid 301 302 10m; # proxy_cache_valid any 1m; # proxy_cache_use_stale error timeout http_500 http_502 http_503 http_504; proxy_pass http://192.168.1.2/index.html; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } }
使用ab进行压力测试。注:-n表示每次并发量,-c表示总共发送的数量
接下来我们将Nginx服务器上的缓存注释取消,在进行缓存测试。
总结:
显而易见,静态资源缓存起到了近3倍的提升,对于服务器需要响应大量并发请求来说提升的还是蛮重要的!当然本章只是介绍了Nginx部分模块,还有很多没有提到,在以后会相继详细介绍。大家有什么问题欢迎交流!
作者:preferred QQ:2517709908
本文出自 “Preferred” 博客,请务必保留此出处http://preferreds.blog.51cto.com/11870667/1870426
以上是关于Nginx实现反向代理负载均衡与静态缓存的主要内容,如果未能解决你的问题,请参考以下文章
Nginx认识与基本使用 Nginx 实现反向代理配置负载均衡
Nginx认识与基本使用 Nginx 实现反向代理配置负载均衡