、安装Tomcat(略)
2、下载安装Nginx
Nginx下载地址:http://nginx.org/en/download.html
下载nginx for windows 1.8.0
下载完成之后,直接解压就可以。我把它放在了D:\Program Files-k\nginx-1.8.0这个路径下。
打开cmd,转到安装目录下 运行start nginx 安装,如下图所示:
如果安装失败,查看80端口是不是被占用,可以用netstat -a 查看
如果一个小黑框一闪而过则表示成功了。我们可以打开任务管理器查看到正在运行的进程。如下图所示:
此时访问 http://localhost/显示下图
就表示第一步成功了~!!!
3、Nginx配置文件nginx.conf
在\nginx-1.8.0\conf目录下有一个nginx.conf文件,有如下代码
server {
listen 80;
server_name localhost;
location / {
root html;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
listen 80;表示监听80端口.
server_name localhost; 表示转到本地,这里指Nginx的文件夹里。
location / 表示匹配的路径, 斜杠代表匹配所有的请求。
root html; 静态文件的路径,其实就是指D:\Program Files-k\nginx-1.8.0\html 这个路径。
index 指当没有指定主页时,默认的指定文件。
4、访问localhost转到tomcat
location / {
proxy_pass http://127.0.0.1:8080;
}
- 1
- 2
- 3
改这一个地方就可以了,表示匹配到任意请求的时候都直接转发给本机的tomcat处理。
然后需要reload一下Nginx,命令 nginx -s reload
这时候再访问 http://localhost/ 就是tomcat 的主页啦~
5、请求分发
实现 http://local.server.com 访问本地的工程,http://linux.server.com访问linux服务器上的工程(在阿里上的虚拟主机)。
首先要修改一下本机的一个文件 C:\Windows\System32\drivers\etc\hosts 最下面加一行
127.0.0.1 local.server.com
127.0.0.1 linux.server.com
- 1
- 2
如下图:
修改nginx.conf配置文件
server {
listen 80;
server_name local.server.com;
location / {
proxy_pass http://127.0.0.1:8080;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
server {
listen 80;
server_name linux.server.com;
location / {
proxy_pass http://10.112.13.56:8080;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
这时候访问http://local.server.com /(你的工程目录)
就可以访问本机的工程,http://linux.server.com/(你的工程目录)
就可以访问linux上的工程啦。如果不想加工程目录,直接用http://local.server.com这个url访问,还需要修改tomcat的server.xml配置文件,在 apache-tomcat-7.0.63-web/conf/server.xml 的最下面的 上面一行添加:
<Context path="" docBase="D:\Program Files-k\apache-tomcat-7.0.62\webapps\examples" reloadable="true" distributable="true"/>
- 1
doBase里面是工程的路径。
6、负载均衡
在server的上面加一个 upstream,如下所示:
我本机的ip地址是192.168.31.111,同一局域网下,小伙伴的ip地址是192.168.31.105,两个人的tomcat都启动,运行相同的工程。
upstream dis{
server 192.168.31.105:8080;
server 127.0.0.1:8080;
}
server{
listen 80;
server_name local.server.com;
location / {
proxy_pass http://dis;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
这时候访问http://local.server.com /(你的工程目录)
,然后不断刷新,你会发现每次请求会间隔的从不同服务器获取内容。这时候两个服务器的比重是1:1。可以通过改变 weight的指改变相应的比重。如下图所示:
upstream dis{
server 192.168.31.105:8080 weight=1;
server 127.0.0.1:8080 weight=3;
}
- 1
- 2
- 3
- 4
负载均衡就完成啦~~!!!!