介绍一下使用Nginx
反向代理来做负载均衡,只需要配置upstream
并选择负载均衡策略,再配置server
反向代理功能就全部搞定了。
1.架设Nginx服务
直接使用Docker
启动一台虚拟Nginx
服务器。
|
2.配置Nginx服务——反向代理与负载均衡
Nginx
的主配置文件位于/etc/nginx/nginx.conf
中。默认内容如下:
|
3.
以下给出一份配置文件,主要用于Nginx
往Tomcat
转发的负载均衡。我在Docker
中虚拟出了5台Tomcat
服务器(192.168.1.[19-23])
。其中,由两台Tomcat
服务器组成了Web Server 1
服务器组(采用ip_hash
算法,就是根据ip做转发)。用3台Tomcat
组成了Web Server 2
服务器组(设置服务器转发权重)。
e.g.
|
可以很明显的看到/etc/nginx/conf.d/*.conf
中的所有.conf
后缀的都会被自动加载作为配置文件。为此,自定义配置文件时,直接在conf.d
目录下新建后缀为.conf
的文件即可。
4.
一些注意事项
有几点需要注意的,Nginx
收到请求之后,会获取请求的Host
字段,然后根据Host
内容匹配server_name
然后转发给不同的server
。转发时直接使用proxy_pass
指令即可,路径中可以写upstream
以实现负载均衡。
5.
配置hosts文件
由于,这里只启动了一台IP为192.168.1.13
的Nginx服务器,那么在我的开发机(Windows 10,192.168.1.2)
上的C:\Windows\System32\drivers\etc\hosts
文件中可以做以下映射。
|
6.
浏览器访问Nginx服务器
好了,测试Nginx
配置文件的有效性(这里-t
后不需要添加任何内容,不要写成nginx -t /etc/nginx/nginx.conf
):
|
重新载入Nginx
|
此时,就可以在开发机的浏览器中访问Nginx
服务器,查看具体的反向代理与负载均衡效果了:
|
小结:
正向代理隐藏真实客户端,反向代理隐藏真实服务端。
nginx 的配置
常用三个命令
start nginx
nginx -s reload #修改配置后载入新的配置
nginx -s stop
1.单域名映射到多服务
server {
listen 80;
server_name www.demo.com;
location /sewage/ {
proxy_pass http://192.168.0.66:32322/;
}
location /sewageserver/ {
proxy_pass http://192.168.0.66:32321/;
}
location /abc/ {
proxy_pass http://192.168.0.66:9004/;
}
location / {
proxy_pass http://192.168.0.66:9000/;
}
}
2.多域名映射到多服务
server {
listen 80;
server_name pro.letv.com;
location / {
proxy_pass http://192.168.0.66:9000/;
}
}
server {
listen 80;
server_name vid.atm.youku.com;
location / {
proxy_pass http://192.168.0.66:9999/;
}
}