将 nginx 容器设置为另一个应用程序的代理

setting nginx container as a proxy for another app

我正在尝试设置一个 nginx 容器,它将在“http://server_ip/”路径上显示 nginx html 页面,在“/app”路径上显示 tutum/hello-world 容器。作为后续行动,希望能够仅从“http://server_ip/app”路径而不是通过 http://server_ip:1500.

我创建了以下 docker-compose:

version: '3'
services: 
  proxy:
    container_name: proxy
    image: nginx
    ports:
      - "80:80"
    volumes:
      - $PWD/html:/usr/share/nginx/html
      - $PWD/config/nginx.conf:/etc/nginx/conf.d/nginx.conf
    networks: 
      - backend
  webapp:
    container_name: webapp
    image: tutum/hello-world
    ports: 
      - "1500:80"
    networks: 
      - backend
networks: 
  backend:

然后我有以下 nginx.conf 文件:

server {
    listen 80; # not really needed, but more informative
    location = / {
        root /usr/share/nginx/html;
    }
    location = /app/ {
        proxy_pass http://localhost:1500/;
    }
}

如果我尝试通过它们的 http://server_ip:PORT 访问每个容器,我就可以到达那里。如果我尝试 http://server_ip/app 我会收到“404 not found”。我错过了什么?我是否将 conf 文件放在了错误的文件夹中?如何将“hello-world”的可用性仅限于“http://server_ip/app”路径,而不是通过“http://server_ip:1500”。

您的容器使用“后端”docker 网络,如您在撰写文件中所述。 在它们内部,它们通过服务名称相互联系,因此从“代理”服务您可以在 http://webapp(或 http://webapp:80)上访问“webapp”服务,从“webapp”服务您可以在 http://proxy 或 (http://proxy:80) 上到达“代理”。

在您的计算机上,如果您键入 http://localhost:1500/,您将访问 webapp 服务,如果您键入 http://localhost:80/,您将访问代理服务。 端口映射1500:80表示你电脑1500端口映射到webapp容器80端口

所以在 nginx.conf 中这样做:

proxy_pass http://webapp:80/;

此外,如果您想让您的 webapp 无法从您的主机访问 localhost:1500,请删除 webapp 服务规范中的端口部分:

version: '3'
services: 
  proxy:
    container_name: proxy
    image: nginx:1.11
    ports:
      - "80:80"
    volumes:
      - $PWD/html:/usr/share/nginx/html
      - $PWD/nginx.conf:/etc/nginx/conf.d/default.conf
    networks: 
      - backend
  webapp:
    container_name: webapp
    image: tutum/hello-world
    networks: 
      - backend
networks: 
  backend: