环境:
ip | 角色 |
192.168.28.112 | tomcat7 |
192.168.28.113 | nginx1.12 |
192.168.28.114 | tomcat7 |
在114和112上安装tomcat,。在113上安装nginx
确保安装成功并都可以成功启动。
实现nginx负载均衡tomcat非常简单,我们一步步来吧。
1.切换到nginx的安装目录:
[root@node113 ~]#cd /usr/local/nginx/conf
2.备份一下nginx的默认配置文件nginx.conf:
[root@node113 /usr/local/nginx/conf]#cp nginx.conf nginx_bak.conf
3.新建一个nginx.conf,全部的配置内容如下:
worker_processes 1; events { worker_connections 1024; } http { upstream aaa { server 192.168.28.112:8080; server 192.168.28.114:8080; } include mime.types; default_type application/octet-stream; sendfile on; server { listen 80; server_name localhost; location / { root html; index index.html index.htm; proxy_pass http://aaa; } } }
解释:
worker_processes 是配置cpu核数,worker_processes和后面的events都是原来nginx.conf中默认的配置。
upstream:用于配置nginx要负载的服务器列表,aaa是你随便起的名字,是你服务器集群的名字。唯一的作用就是要和下面proxy_pass的
属性值保持一致,如这里写aaa,那么proxy_pass的值就是http://aaa。如果你以后增加了服务器需要让nginx负载均衡,在upstream中加一条记录
即可,是不是相当的简便!
include、default_type、sendfile都是原来nginx.conf中默认的配置,这里不牵涉到负载均衡,先不说了。
server_name和listen指定了nginx安装机器的ip以及端口
location 配置将要被nginx拦截的路径,/表示全部拦截
proxy_pass :标识负载到哪个upstream上,这里选择之前配置的aaa上
释疑:
aaa的作用只是给upstream代表的服务器集群起个标识,以便于下面的proxy_pass对应,我们配置好负载均衡之后的访问路径跟aaa毫无
关系。
4.在112和114机器的tomcat的webapps下面分边建立个文件夹,名字叫做myweb,里面新建一个test.html,112上的test.html内容:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>测试页面</title> </head> <body> <p>112上的test.html</p> </body> </html>
114上内容改一下:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>测试页面</title> </head> <body> <p>114上的test.html</p> </body> </html>
这样做的目的是等下可以看到具体访问的是哪个页面。
5.重启nginx
[root@node113 /usr/local/nginx/sbin]#./nginx -s reload
6.启动112和114上的tomcat:
[root@node112 /usr/tomcat/apache-tomcat-7.0.77/bin]#./startup.sh [root@node114 /usr/tomcat/apache-tomcat-7.0.77/bin]#./startup.sh
先通过tomcat访问test.html,如下:
两台tomcat是没有问题的。
7.我们访问nginx看看吧http://192.168.28.113/myweb/test.html:
刷新页面:
不断的刷新页面,我们可以看到页面将会在上边两张图均匀的切换,实现了负载均衡。