参考文章:
Nginx反向代理两个tomcat服务器 - 戈博折刀 - 博客园
Nginx负载均衡的详细配置及使用案例详解. - 一枝花算不算浪漫 - 博客园
nginx反向代理proxy_pass绝对路径和相对路径 - 简书
1. 安装依赖包
yum install gcc-c++
yum install -y pcre pcre-devel
yum install -y zlib zlib-devel
yum install -y openssl openssl-devel
make
make install
2. 下载解压nginx(最新稳定版本)
wget http://nginx.org/download/nginx-1.20.1.tar.gz
tar -zxvf nginx-1.20.1.tar.gz -C /usr/local/nginx
3. 使用默认配置
cd /usr/local/nginx-1.20.1
./configure
4. 启动
cd /usr/local/nginx/sbin
./nginx 启动
./nginx -s stop 强制关闭
./nginx -s quit 关闭
./nginx -s reload 重载服务配置文件
./nginx -t 验证配置文件
./nginx -c 路径 配置文件路径
5. 配置文件
/usr/local/nginx/conf/nginx.conf
vim nginx.conf
6. 开放端口
firewall-cmd --zone=public --add-port=80/tcp --permanent
firewall-cmd --reload
7. 配置反向代理,负载均衡
先配置转发请求的真正服务地址,即真正响应服务的tomcat的地址和端口,
用 upstream + 自定义tomcat服务器的名称,然后里面是 server + tomcat的ip+端口
(server_name拦截请求域名,本地主机需修改host文件 ip 域名 )
192.168.199.100 8080.主机名.com
192.168.199.100 8081.主机名.com
location中,不再配置本地目录作为相应,而是用 proxy_pass 关键字来配置请求转发的服务器名称,具体格式为: proxy_pass http:// + 服务器名称
其中的服务名称就是我们在 upstream 中配置的 真正要提供服务的tomcat的 我们自定义的名称,即 tomcatserver1
这样,当前台请求 虚拟主机的拦截地址 8080.itheima.com时,虚拟主机就会将请求转发给真正的tomcat服务器 192.168.25.141:8080 来提供服务。
同理,再配置第二对请求的真正服务器 tomcatserver2 及 拦截请求的虚拟主机 server_name 8081.itheima.com
实例:
vim /usr/local/nginx/conf/nginx.conf
配置文件内容:
upstream tomcatserver1{
server 192.168.199.100:8080 weight=2;
server 192.168.199.100:8081 weight=1;
}
upstream tomcatserver2{
server 192.168.199.100:8081;
}
server{
listen 80;
server_name 8080.主机名.com;
location / {
proxy_pass http://tomcatserver1;
index index.html index.htm;
}
}
第二台服务器:
server{
listen 80;
server_name 8081.主机名.com;
location / {
proxy_pass http://tomcatserver2;
index index.html index.htm;
}
}
访问 8080.主机名.com
访问 8081.主机名.com
这样就实现了反向代理,即从表象上看,我们两个请求都是请求的同一个ip地址同样都是默认的80端口,但是服务器端实际上是用两个不同的tomcat来响应的。
因为我们前面在host中配置的是同一个ip,而且没有配端口(后面的8080和8081后面都是点,即其是域名,非端口),所以看起来像是访问的同一个服务器ip地址和端口。
8. 负载均衡
upstream tomcatserver{
server 192.168.199.100:8080 weight=2;
server 192.168.199.100:8081 weight=1;
}
server{
listen 80;
server_name 8080.主机名.com;
location / {
proxy_pass http://tomcatserver;
index index.html index.htm;
}
}
访问nginx主机8080.主机名.com的请求会被拦截,并转发到http://tomcatserver 下,其中服务器对应的
192.168.199.100:8080
192.168.199.100:8081
含有对应权重,按权重比例转发请求。
proxy_pass 的相对路径和绝对路径
在nginx中配置proxy_pass代理转发时,如果在proxy_pass后面的url加/,表示绝对根路径;如果没有/,表示相对路径,把匹配的路径部分也给代理走
其他配置:
超时时间、最大请求数、数据包发送、隐藏版本号、日志配置、文件缓存、ssl证书等配置。