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

概述

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

反向代理主要应用场景

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

使用 Nginx 反向代理 Tomcat

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

version: '3.1'
services:
  nginx:
    restart: always
    image: nginx
    container_name: nginx
    ports:
      - 80:80
    volumes:
      - ./conf/nginx.conf:/etc/nginx/nginx.conf
      - ./wwwroot:/usr/share/nginx/wwwroot

启动 Tomcat 容器

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

version: '3'
services:
  tomcat1:
    image: tomcat
    container_name: tomcat1
    ports:
      - 9090:8080

  tomcat2:
    image: tomcat
    container_name: tomcat2
    ports:
      - 9091:8080

配置 Nginx 反向代理

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

user  nginx;
worker_processes  1;

events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;

    sendfile        on;

    keepalive_timeout  65;
    
    # 配置一个代理即 tomcat1 服务器
    upstream tomcatServer1 {
        server 192.168.50.136:9090;
    }

    # 配置一个代理即 tomcat2 服务器
    upstream tomcatServer2 {
        server 192.168.50.136:9091;
    }

    # 配置一个虚拟主机
    server {
        listen 80;
        server_name tomcat1.myapp.com;
        location / {
                # 域名 tomcat1.myapp.com 的请求全部转发到 tomcatServer1 即 tomcat1 服务上
                proxy_pass http://tomcatServer1;
                # 欢迎页面,按照从左到右的顺序查找页面
                index index.jsp index.html index.htm;
        }
    }

    server {
        listen 80;
        server_name tomcat2.myapp.com;

        location / {
            # 域名 tomcat2.myapp.com 的请求全部转发到 tomcatServer2 即 tomcat2 服务上
            proxy_pass http://tomcatServer2;
            index index.jsp index.html index.htm;
        }
    }
}

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

配置 Nginx 负载均衡

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

user  nginx;
worker_processes  1;

events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;

    sendfile        on;

    keepalive_timeout  65;
    
    # 配置代理
    upstream tomcatServer {
        server 192.168.50.136:9090 weight=10;
        server 192.168.50.136:9091 weight=10;
    }

    # 配置一个虚拟主机
    server {
        listen 80;
        server_name tomcat.myapp.com;
        location / {
                # 域名 tomcat.myapp.com 的请求全部转发到 tomcatServer 服务上
                proxy_pass http://tomcatServer;
                # 欢迎页面,按照从左到右的顺序查找页面
                index index.jsp index.html index.htm;
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_41779565/article/details/124076479
今日推荐