繁体   English   中英

在 docker-compose 内使用 nginx 托管 web 页面:无法解析主机名

[英]Hosting web page with nginx inside docker-compose: Can't resolve hostname

我的设置如下:

  1. 后端:Flask 服务器运行在 5000 端口; 在 python 中实现
  2. 前端:React 应用程序向后端发送 http 请求
  3. 两者都使用 docker-compose 进行了 dockerized 并在同一节点上运行

我的 docker-compose 文件:

version: "3"
services:
  backend:
    ports:
      - "5000:5000"
    image: <backend-image>

  frontend:
    depends_on:
      - backend
    ports:
      - "80:80"
    links:
      - "backend:backend-python"
    image: <frontend-image>

nginx.conf

server {
    listen       80;
    server_name  localhost;
    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
        try_files $uri /index.html;                 
    }
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}

我从前端向http://backend-python:5000/<my-endpoint>发送请求。 backend-python在 docker-compose 的前端规范中定义为后端的主机名。 当我在本地运行docker-compose up并在浏览器中打开localhost时,页面会按预期显示。 当我在 Raspberry Pi 3 上运行docker-compose up ,当我在笔记本电脑上本地打开页面时,前端无法解析http://backend-python:5000/<my-endpoint>

我还尝试将nginx替换为使用serve服务构建。 这导致与上述相同的行为。

从谷歌搜索来看,在我看来,使用 docker-compose 构建了自己的网络,其中每个容器都可以通过其名称或在links下定义的名称找到。

有人知道为什么从其他机器访问页面时无法解析名称吗?

前端应用程序在浏览器中运行,当前端应用程序尝试访问 API 时,是浏览器尝试与之通信。

When you host a frontend app inside docker with nginx, all the container do is to server the static file needed by the browser, but it's not nginx that try to communicate with your API.

这就是为什么您的浏览器无法使用容器名称访问您的后端的原因,您需要公开您的 API 并在您的前端应用程序中更改 API/后端 URL 以使用http://localhost:5000

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM