负载均衡
<h1>负载均衡配置</h1>
<ul>
<li>Nginx总结(六)nginx实现负载均衡</li>
<li><a href="https://www.cnblogs.com/zhangweizhong/p/11378566.html">https://www.cnblogs.com/zhangweizhong/p/11378566.html</a></li>
</ul>
<h2>负载均衡简介</h2>
<ul>
<li>负载均衡是建立在现有网络结构之上,它提供了一种廉价有效透明的方法扩展网络设备和服务器的带宽、增加吞吐量、加强网络数据处理能力、提高网络的灵活性和可用性。</li>
<li>负载均衡,英文名称为Load Balance,其意思就是分摊到多个操作单元上进行执行
<ul>
<li>例如Web服务器、FTP服务器、企业关键应用服务器和其它关键任务服务器等,从而共同完成工作任务。</li>
</ul></li>
</ul>
<h2>应用场景</h2>
<ul>
<li>nginx 作为负载均衡服务器,用户请求先到达 nginx,再由 nginx 根据负载配置将请求转发至 tomcat 服务器。</li>
</ul>
<table>
<thead>
<tr>
<th>服务器名称</th>
<th>IP地址</th>
</tr>
</thead>
<tbody>
<tr>
<td>nginx负载均衡服务器</td>
<td>192.168.32.150</td>
</tr>
<tr>
<td>tomcat1 服务器</td>
<td>192.168.32.151</td>
</tr>
<tr>
<td>tomcat2 服务器</td>
<td>192.168.32.152</td>
</tr>
</tbody>
</table>
<h2>环境准备</h2>
<ul>
<li>nginx 服务器是
<ul>
<li>192.168.32.128</li>
</ul></li>
<li>2台 tomcat 服务器,我这里使用的是使用 apache-tomcat-7.0.57版本
<ul>
<li>在 192.168.32.151 和 192.168.32.152 虚拟机上启动 tomcat</li>
</ul></li>
<li>
<p>修改2个 tomcat 下的 webapps/ROOT/index.jsp 的内容,使用 tomcat1 和 tomcat2 两个服务首页显示不同的内容。</p>
</li>
<li>通过 host 文件指定 www.141proxy.com 和 www.142proxy.com 对应 192.168.32.128虚拟机
<ul>
<li>修改window的hosts文件位置(C:\Windows\System32\drivers\etc)</li>
<li>192.168.32.150 www.150load.com</li>
</ul></li>
</ul>
<h2>进行配置</h2>
<ul>
<li>
<p>增加配置文件</p>
<pre><code class="language-shell">cd /usr/local/nginx/conf/vhosts
www.150load.com.conf</code></pre>
</li>
<li>
<p>文件 www.150load.com.conf 增加内容</p>
<pre><code class="language-nginx">upstream tomcat_server_pool{
server 192.168.32.151:8080 weight=10;
server 192.168.32.152:8080 weight=10;
}
server {
listen 80;
server_name www.150load.com;
location / {
proxy_pass http://tomcat_server_pool;
index.html index.htm index.php;
}
}</code></pre>
</li>
<li>
<p>相关参数说明</p>
</li>
<li>
<p>down</p>
<ul>
<li>单前的server暂时不参与负载</li>
</ul>
</li>
<li>
<p>weight</p>
<ul>
<li>默认为1,weight越大,负载的权重就越大</li>
</ul>
</li>
<li>
<p>max_fails</p>
<ul>
<li>允许请求失败的次数默认为1,当超过最大次数时,返回proxy_next_upstream 模块定义的错误</li>
</ul>
</li>
<li>
<p>fail_timeout</p>
<ul>
<li>max_fails 次失败后,暂停的时间。</li>
</ul>
</li>
<li>
<p>backup</p>
<ul>
<li>其它所有的非 backup 机器 down 或者忙的时候,请求 backup 机器。所以这台机器压力会最轻</li>
</ul>
</li>
</ul>
<h2>测试</h2>
<ul>
<li>
<p>重新启动nginx,观察端口监听状态</p>
<pre><code class="language-shell">systemctl restart nginx
ps aux | grep nginx</code></pre>
</li>
<li>
<p>访问 <a href="http://www.150load.com">http://www.150load.com</a></p>
<ul>
<li>多刷新几次浏览器,分别显示各自服务器上文件的内容</li>
</ul>
</li>
</ul>