linux系统下配置nginx负载均衡

138 阅读1分钟

感谢博主:www.cnblogs.com/lave/p/1047…

首先准备两个服务器:

分别都启动一个tomcat,tomcat的root文件下放入test.jsp文件,可以插入代码,其中一个服务器配置nginx,nginx配置完后可以吧默认端口改为70,这里有个坑点,需要在阿里云上面解开70端口,不然访问不了nginx:

在nginx.conf文件里面配置(在http里面):

 #设定负载均衡的服务器列表和加个service主机:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Test Page</title>
</head>
<body>
KeYing Page!!!<br/>
remote ip :   <%=request.getHeader("X-real-ip") %>  <br/>
nginx server ip : <%=request.getRemoteAddr()%>
</body>
</html>

upstream taishan {
    #weigth参数表示权值,权值越高被分配到的几率越大
    #下面表示137有3分之2几率,138有3分之1几率
    server 10*******:8080  weight=1 max_fails=2 fail_timeout=30s;   
    #server 47*******:8080  weight=1 max_fails=2 fail_timeout=30s;   
    server *******.cn:8080  weight=2 max_fails=2 fail_timeout=30s;   
} 
#下面是server虚拟主机的配置
 server
  {
    listen 70;#监听端口
    server_name localhost;#域名
    index index.html index.htm index.php;
    root /usr/local/webserver/nginx/html;#站点目录
	 location / {
           #root   html;
           #index  index.html index.htm;
		    #设置客户端真实ip地址
			proxy_set_header X-real-ip $remote_addr;   
			proxy_pass http://taishan;#请求转向taishan定义的服务器列表
		   proxy_set_header Host $host;#将请求头转发给后端服务器
		   #proxy_set_header X-Forward-For $remote_addr;#后端的Web服务器可以通过X-Forwarded-For获取用户真实IP
		   #其他相关配置入下,可以根据需要添加配置
		   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服务器传
        }
      location ~ .*\.(php|php5)?$
    {
      #fastcgi_pass unix:/tmp/php-cgi.sock;
      fastcgi_pass 127.0.0.1:9000;
      fastcgi_index index.php;
      include fastcgi.conf;
    }
    location ~ .*\.(gif|jpg|jpeg|png|bmp|swf|ico)$
    {
      expires 30d;
  # access_log off;
    }
    location ~ .*\.(js|css)?$
    {
      expires 15d;
   # access_log off;
    }
    access_log off;
  }

linux启动nginx:

./sbin/nginx

停止:./sbin/nginx -s stop

重新加载配置:./sbin/nginx -s reload

重启:./sbin/nginx -s reopen

启动成功后:

访问nginx:http://10----:70/test.jsp

就可以看到页面: