CentOS中nginx负载均衡和反向代理的搭建
1:配置虚拟主机:
1、nginx支持的三种虚拟主机的配置:
基于ip的虚拟主机
基于域名的虚拟主机
基于端口的虚拟主机
2、nginx配置文件的结构: 每个service就是一个虚拟主机
......
events{
......
}
http{
.......
server{
......
}
server{
......
}
}
3、基于ip的虚拟主机配置:
修改配置文件: vim /usr/local/nginx/nginx-1.8.0/conf/nginx.conf
server{
listen 80;
server_name 192.168.31.88;
location / {
root html;
index index.html index.htm;
}
}
4、基于域名的虚拟主机配置:
修改配置文件:vim /usr/local/nginx/nginx-1.8.0/conf/nginx.conf
server{
listen 80;
server_name www.nginxdns1.com;
location / {
root html_dns1;
index index.html index.htm;
}
}
server{
listen 80;
server_name www.nginxdns2.com;
location / {
root html_dns2;
index index.html index.htm;
}
}
5、基于端口的虚拟主机配置:
修改配置文件:vim /usr/local/nginx/nginx-1.8.0/conf/nginx.conf
监听端口:netstat -an | grep 80
server{
listen 88;
server_name 192.168.31.88;
location / {
root html_port1;
index index.html index.htm;
}
}
server{
listen 89;
server_name 192.168.31.88;
location / {
root html_port2;
index index.html index.htm;
}
}
2、nginx 反向代理:
修改hosts:# nginx反向代理环境测试
192.168.31.88 www.nginxproxy1.com
192.168.31.88 www.nginxproxy2.com
开启不同虚拟机中的两台tomcat:192.168.31.88:8080 和 192.168.31.89:8081
修改配置文件:
#代理tomcat1服务器
upstream tomcat_server1{
server 192.168.31.89:8081;
}
#代理tomcat2服务器
upstream tomcat_server2{
server 192.168.31.88:8080;
}
#配置虚拟主机:
server{
listen 80;
server_name www.nginxproxy1.com;
location / {
#root html_port1;
proxy_pass http://tomcat_server1;
index index.html index.htm;
}
}
server{
listen 80;
server_name www.nginxproxy2.com;
location / {
#root html_port2;
proxy_pass http://tomcat_server2;
index index.html index.htm;
}
}
3、nginx 负载均衡:
修改hosts :# nginx负载均衡环境测试
192.168.31.88 www.nginxbalance.com
开启不同虚拟机中的两台tomcat:192.168.31.88:8080 和 192.168.31.89:8081
修改配置文件:
#代理tomcat2服务器
upstream tomcat_server_pool{
server 192.168.31.88:8080 weight=1;
server 192.168.31.89:8081 weight=1;
}
#配置虚拟主机:
server{
listen 80;
server_name www.nginxbalance.com;
location / {
#root html_port1;
proxy_pass http://tomcat_server_pool;
index index.html index.htm;
}
}
hosts文件配置:
1:nginx基于域名环境测试
192.168.31.88 www.nginxdns1.com
192.168.31.88 www.nginxdns2.com
2:nginx反向代理环境测试
192.168.31.88 www.nginxproxy1.com
192.168.31.88 www.nginxproxy2.com
3:nginx负载均衡环境测试
192.168.31.88 www.nginxbalance.com