nginx实现反向代理和负载均衡

利用nginx做反向代理和负载均衡是减轻服务器压力的有效方式。nginx代理服务器接收多个客户端请求,

根据配置的参数均衡到每个tomcat服务器上,tomcat处理请求,返回响应结果给nginx,nginx再返回给指定客户端。

而一些静态的资源可以由nginx直接返回给客户端。这样减轻了tomcat服务器的压力,如下图。

nginx实现反向代理和负载均衡

反向代理:代理服务器,利用代理服务器接收请求及返回响应内容

正向代理:代理客户端,如VPN,是改变客户端的节点

利用nginx做反向代理需要在nginx.conf的server中添加proxy_pass,并且远程访问的ip会变成

nginx代理服务器的ip,需要在请求头中原客户端的ip地址:

proxy_set_header X-real-ip $remote_addr;
proxy_pass http://myupstream;

这里myupstream是upstream流的名称,upstream是用来做负载均衡的,在http的配置内容下定义upstream

#负载均衡配置
upstream myupstream {
server 192.168.18.128:8080 weight=1 max_fails=2 fail_timeout=30s;
server 192.168.18.128:8081 weight=1 max_fails=2 fail_timeout=30s;
}

负载均衡有下面几个参数:

weight:基于权重,weight值越高被访问的频率越高,这里8080和8081的访问频率相等,采用轮询,一次8080,一次8081

 server 192.168.18.128:8080 weight=1 ;
server 192.168.18.128:8081 weight=1;

ip hash:同一ip访问同一服务器,当同一个客户端ip访问时,会使用上次处理的服务器,

不会造成上一次访问存在另一台服务器上的会话信息丢失问题 。

upstream myupstream {
server 192.168.18.128:8080 weight=1 max_fails=2 fail_timeout=30s;
server 192.168.18.128:8081 weight=1 max_fails=2 fail_timeout=30s;
ip hash;
}

fair:基于响应时间,每次都会将请求转发给响应时间更短的服务器处理

upstream myupstream {
server 192.168.18.128:8080 weight=1 max_fails=2 fail_timeout=30s;
server 192.168.18.128:8081 weight=1 max_fails=2 fail_timeout=30s;
fair;
}

下面是nginx代理服务器的全部配置:

worker_processes 1;

events {
worker_connections 1024;
} http {
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/test1.log main;
include mime.types;
default_type application/octet-stream;
fastcgi_intercept_errors on;
charset utf-8;
server_names_hash_bucket_size 128;
client_header_buffer_size 4k;
large_client_header_buffers 4 32k;
client_max_body_size 300m;
sendfile on;
tcp_nopush on;
keepalive_timeout 60; tcp_nodelay on;
client_body_buffer_size 512k;
proxy_connect_timeout 5;
proxy_read_timeout 60;
proxy_send_timeout 5;
proxy_buffer_size 16k;
proxy_buffers 4 64k;
proxy_busy_buffers_size 128k;
proxy_temp_file_write_size 128k;
gzip on;
gzip_min_length 1k;
gzip_buffers 4 16k;
gzip_http_version 1.1;
gzip_comp_level 2;
gzip_types text/plain application/x-javascript text/css application/xml;
gzip_vary on; #负载均衡配置
upstream myupstream {
server 192.168.18.128:8080 weight=1 max_fails=2 fail_timeout=30s;
server 192.168.18.128:8081 weight=1 max_fails=2 fail_timeout=30s;
}
server{
listen 80;
server_name nginx.test.com;
access_log logs/test1.log main;
location /{
proxy_set_header X-real-ip $remote_addr;
proxy_pass http://myupstream;
root html; index index.html index.htm;
}
} server{
listen 81;
server_name nginx.test1.com;
location /{
root html;
index index.html index.htm;
}
} server {
listen 82;
server_name nginx.test2.com; location / {
root html;
index index.html index.htm;
} error_page 500 502 503 504 /50x.html;
location = /50x.html { root html;
}
}
}
上一篇:nginx的反向代理和负载均衡的一个总结


下一篇:mysql5.6 主从复制