Nginx 配置反向代理、负载均衡

概述

反向代理服务器架设在服务器端,通过缓冲经常被请求的页面来缓解服务器的工作量,将客户机请求转发给内部网络上的目标服务器;并将从服务器上得到的结果返回给 Internet 上请求连接的客户端,此时代理服务器与目标主机一起对外表现为一个服务器。

反向代理主要应用场景

许多大型 web 网站都用到反向代理。除了可以防止外网对内网服务器的恶性攻击、缓存以减少服务器的压力和访问安全控制之外,还可以进行负载均衡,将用户请求分配给多个服务器。

使用 Nginx 反向代理 Tomcat

我们使用 Docker 来安装和运行 Nginx,docker-compose.yml 配置如下:

  1. version: '3.1'
  2. services:
  3. nginx:
  4. restart: always
  5. image: nginx
  6. container_name: nginx
  7. ports:
  8. - 80:80
  9. volumes:
  10. - ./conf/nginx.conf:/etc/nginx/nginx.conf
  11. - ./wwwroot:/usr/share/nginx/wwwroot

启动 Tomcat 容器

启动两个 Tomcat 容器,映射端口为 90909091docker-compose.yml 如下:

  1. version: '3'
  2. services:
  3. tomcat1:
  4. image: tomcat
  5. container_name: tomcat1
  6. ports:
  7. - 9090:8080
  8. tomcat2:
  9. image: tomcat
  10. container_name: tomcat2
  11. ports:
  12. - 9091:8080

配置 Nginx 反向代理

修改 /usr/local/docker/nginx/conf 目录下的 nginx.conf 配置文件:

  1. user nginx;
  2. worker_processes 1;
  3. events {
  4. worker_connections 1024;
  5. }
  6. http {
  7. include mime.types;
  8. default_type application/octet-stream;
  9. sendfile on;
  10. keepalive_timeout 65;
  11. # 配置一个代理即 tomcat1 服务器
  12. upstream tomcatServer1 {
  13. server 192.168.50.136:9090;
  14. }
  15. # 配置一个代理即 tomcat2 服务器
  16. upstream tomcatServer2 {
  17. server 192.168.50.136:9091;
  18. }
  19. # 配置一个虚拟主机
  20. server {
  21. listen 80;
  22. server_name tomcat1.myapp.com;
  23. location / {
  24. # 域名 tomcat1.myapp.com 的请求全部转发到 tomcatServer1 即 tomcat1 服务上
  25. proxy_pass http://tomcatServer1;
  26. # 欢迎页面,按照从左到右的顺序查找页面
  27. index index.jsp index.html index.htm;
  28. }
  29. }
  30. server {
  31. listen 80;
  32. server_name tomcat2.myapp.com;
  33. location / {
  34. # 域名 tomcat2.myapp.com 的请求全部转发到 tomcatServer2 即 tomcat2 服务上
  35. proxy_pass http://tomcatServer2;
  36. index index.jsp index.html index.htm;
  37. }
  38. }
  39. }

注意:新版 Nginx 的 upstream 配置中的名称不可以有下划线(_),否则会报 400 错误

配置 Nginx 负载均衡

修改 /usr/local/docker/nginx/conf 目录下的 nginx.conf 配置文件:

  1. user nginx;
  2. worker_processes 1;
  3. events {
  4. worker_connections 1024;
  5. }
  6. http {
  7. include mime.types;
  8. default_type application/octet-stream;
  9. sendfile on;
  10. keepalive_timeout 65;
  11. # 配置代理
  12. upstream tomcatServer {
  13. server 192.168.50.136:9090 weight=10;
  14. server 192.168.50.136:9091 weight=10;
  15. }
  16. # 配置一个虚拟主机
  17. server {
  18. listen 80;
  19. server_name tomcat.myapp.com;
  20. location / {
  21. # 域名 tomcat.myapp.com 的请求全部转发到 tomcatServer 服务上
  22. proxy_pass http://tomcatServer;
  23. # 欢迎页面,按照从左到右的顺序查找页面
  24. index index.jsp index.html index.htm;
  25. }
  26. }
  27. }

发表评论

表情:
评论列表 (有 0 条评论,86人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Nginx配置反向代理负载均衡

    今天给大家介绍一下如何利用Nginx进行反向代理,之所以介绍这个的原因是,因为开发的时候遇到一个很尴尬的场景。因为是springboot项目,所以每一个控制类的端口都不一样,但