3

只需三步,使用Docker创建Nginx反向代理

 7 months ago
source link: https://www.51cto.com/article/781318.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

在Web架构中,敏捷性和可伸缩性是必不可少的,在管理服务的同时也需要保证最佳性能。

为了达到这一目标,可以使用反向代理。反向代理非常灵活,可简化客户端和服务器之间的交互和通信。

如图所示,反向代理就像大楼里的接待员,该大楼有各个部门和区域。接待员成功地将客户或访客重定向到适当的部门。他们负责指引访客,处理查询,并确保各个部门之间的分发。

图片

图片

反向代理的用途包括:

  1. 用于可伸缩性的负载均衡。
  2. 终止SSL和TLS。
  3. 将子域映射到特定路径。

本文将使用Nginx和Docker容器来设置反向代理。

第1步,创建应用程序

下载完整代码(https://github.com/DiptoChakrabarty/nginx-reverse-proxy)。

我们从构建作为代理的应用程序开始。

编写Docker文件,在访问此应用程序的/端点时显示一个简单的HTML页面。

FROM nginx:stable-alpine
COPY index.html /usr/share/nginx/html/index.html

index.html文件如下:

<h1>This is the main app</h1>

编写一个简单的Docker Compose文件,来运行这个应用程序。

version : '3.7'
services :
  web:
    build: .
    ports:
    - "8080:80"

通过运行以下命令启动Docker Compose:

docker-compose up

访问localhost:8080,应该能够看到以下内容。

图片

图片

以类似的方式创建两个不同的应用程序,使用两个HTML文件和相同的Dockerfile。

This is html file for app1
<h1>This is APP 1</h1>

This is html file for app2
<h1>This is APP 2</h1>

修改Docker Compose文件以启动这两个容器:

version : '3.7'
services :
  web:
    build: .
    ports:
    - "8080:80"
    restart: always
  app1:
    build: ./app1/
    ports:
    - "8085:80"
    restart: always
  app2:
    build: ./app2
    ports:
    - "8010:80"
    restart: always

访问端口8085和8010时,可以看到如下内容:

图片

图片

第2步,编写Nginx配置

编写Nginx配置文件,以在访问/app时,在app1和app2之间进行代理,而在/端点上只显示主页面。

Nginx配置如下所示:

worker_processes  1;  ## Default: 1
worker_rlimit_nofile 8192;

http {
  
  upstream cloud_server_com {
    server app1:80;
    server app2:80;
  }
  server {
    listen   80;
    location /app/ {
      proxy_pass      http://cloud_server_com/;
    }
    location / {
      root   /usr/share/nginx/html;
      index  index.html;
    }
    
  }
}

配置文件定义了组合在一起的服务器组。在这里,我们指定了在Docker Compose文件中定义的容器名称及其端口号。

location帮助Nginx定义如何处理特定端点的请求。/app/将请求发送到cloud_server_com上游,而cloud_server_com就是两个应用程序的容器。

proxy_pass确定了请求将被重定向到哪里。

现在,Docker Compose文件需要能够读取此配置,因此需要修改Compose文件,如下所示:

version : '3.7'
services :
  web:
    build: .
    ports:
    - "8080:80"
    volumes:
      - ./config/nginx.conf:/etc/nginx/nginx.conf
    restart: always
  app1:
    build: ./app1/
    ports:
    - "8085:80"
    restart: always
  app2:
    build: ./app2
    ports:
    - "8010:80"
    restart: always

第3步,运行容器

运行docker-compose up命令,然后在浏览器中查看反向代理的工作原理。

这是在/端点上运行的主应用程序:

图片

图片

但是,在访问/app/端点时,它返回两个不同的服务器,代理逐个发送请求到app1和app2。

图片

图片

图片


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK